<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chris Evans on Medium]]></title>
        <description><![CDATA[Stories by Chris Evans on Medium]]></description>
        <link>https://medium.com/@dynamicy?source=rss-ee0a0984445a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Cn9Es_lTT42kLAZwZUtR-w.jpeg</url>
            <title>Stories by Chris Evans on Medium</title>
            <link>https://medium.com/@dynamicy?source=rss-ee0a0984445a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 18:12:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dynamicy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[Turning an Internal Communication Module into a Custom Python Package]]></title>
            <link>https://medium.com/codecodecode/turning-an-internal-communication-module-into-a-custom-python-package-916f3805d163?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/916f3805d163</guid>
            <category><![CDATA[python-packages]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 18:02:49 GMT</pubDate>
            <atom:updated>2025-11-20T18:02:49.100Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I did something in one of our projects that I’m quietly proud of:<br>I took the device‑communication code that had been scattered across several services, and turned it into a standalone Python package. Our main apps now depend on it via a GitHub dependency instead of copying the same code around.</p><p>In this article I want to record that journey and talk about:</p><ol><li><strong>Why bother creating a custom package in the first place?</strong></li><li><strong>What the project roughly looks like (a safe, anonymized version)</strong></li><li><strong>How I extracted the existing code into a reusable library</strong></li><li><strong>How we use it in real projects via a GitHub dependency</strong></li><li><strong>How I handle versioning and tags</strong></li><li><strong>What benefits it actually brought us, plus a few lessons learned</strong></li></ol><p>Because this is company work, I’ll keep the examples high‑level and avoid any sensitive protocol or business details. But the overall approach should be useful for any team facing similar problems.</p><h3>1. Why turn it into a custom package?</h3><p>The original context was simple enough:<br>We have a piece of hardware (think access control device / controller board) that we talk to via serial or TCP. There’s a proprietary protocol behind it, and our code has to construct and parse those messages correctly.</p><p>Over time, as the system grew, a few pain points started to show up:</p><ul><li><strong>The same communication logic was duplicated in multiple services</strong></li><li>Every small change meant guessing “which services copied this file and then modified it?”</li><li><strong>Writing tests was painful</strong> because communication logic was tightly coupled to business logic</li><li>When onboarding new people, it was hard to explain where the “real” protocol implementation lived</li></ul><p>One day I looked at the code and the only thing in my head was:</p><blockquote><em>“This is clearly a library. Why is it buried inside one specific app?”</em></blockquote><p>So I decided to split it out into a separate, clean Python package whose only job is:<br><strong>“talk to the device using the protocol, and do it well.”</strong></p><h3>2. What does the project look like? (sanitized version)</h3><p>Here’s a simplified directory structure — just enough to show the idea, without any sensitive details:</p><pre>device-protocol/<br>  src/<br>    device_protocol/<br>      transports/<br>        base.py<br>        serial.py<br>        tcp.py<br>      client.py<br>      commands.py<br>      exceptions.py<br>      parsers.py<br>      protocol.py<br>  tests/<br>    test_client.py<br>    test_protocol.py<br>  pyproject.toml<br>  Makefile<br>  README.md</pre><p>The roles of the main modules look like this:</p><ul><li>transports/<br>Abstracts <strong>how</strong> messages are sent:</li><li>SerialTransport (serial port)</li><li>TcpTransport (TCP socket)<br>From the library’s perspective, a transport is just “something that can send and receive bytes.”</li><li>protocol.py<br>Handles converting high‑level operations into protocol frames and parsing responses back into Python structures. It uses helpers like parsers.py and commands.py.</li><li>client.py<br>Exposes a high‑level API like:</li><li>client.unlock(door_id=1)</li><li>client.get_status()</li><li>client.ping()</li><li>tests/<br>Unit and integration tests for the protocol and client behavior. They make sure I don’t break anything when refactoring, even if I’m not connected to the real hardware.</li></ul><p>The core idea: <strong>wrap all the “how to talk to the device” logic into a clean black box.</strong></p><h3>3. From “module inside an app” to “standalone package”</h3><p>Here’s roughly how I did the extraction.</p><h3>3.1 Move the code into a new repo</h3><p>Originally, the code lived inside one of our backend projects.<br>First step:</p><ul><li>Create a new folder, e.g. device-protocol</li><li>Move all device‑communication code into it</li><li>Remove or abstract anything tightly coupled to our business logic (logging style, DB calls, app‑specific concepts, etc.)</li></ul><p>This step felt like refactoring plus decluttering: keep only what is truly part of the protocol; push everything else back to the callers.</p><h3>3.2 Set up a standard Python project layout</h3><p>I like the src layout, so I went with:</p><pre>src/<br>  device_protocol/<br>    ...<br>tests/<br>  ...<br>pyproject.toml</pre><p>Then I initialized the project (Poetry, uv, PDM — whatever you prefer).<br>For example, with Poetry:</p><pre>poetry init</pre><p>After that I:</p><ul><li>Set the project name / version / authors</li><li>Configured device_protocol as the main package</li></ul><h3>3.3 Add tests so extraction doesn’t become guesswork</h3><p>This part took some time, but it paid for itself quickly.</p><p>My approach:</p><ul><li>Start with a few <strong>critical scenarios</strong> as tests (e.g. “normal unlock”, “error response”, “timeout behavior”)</li><li>Use a <strong>fake transport</strong> (in‑memory) to simulate device responses rather than hitting real hardware</li><li>Port over existing test cases from the original app where possible, to keep behavior aligned</li></ul><p>Once all the tests were green, I finally felt comfortable treating this as “the official protocol implementation.”</p><h3>3.4 Put it on GitHub and add basic automation</h3><p>After cleaning things up locally, I:</p><ol><li>Created a GitHub repo (private is fine)</li><li>Pushed the code</li><li>Added a simple GitHub Actions workflow to:</li></ol><ul><li>Install dependencies</li><li>Run lint and pytest</li></ul><p>From that point on, this code was no longer “just part of one app” — <br>it became a <strong>reusable library</strong> with its own lifecycle.</p><h3>4. Using it from the main project via a GitHub dependency</h3><p>The key change on the application side was this:</p><blockquote><em>The communication code is no longer in the app repo;<br>it’s treated like a third‑party dependency.</em></blockquote><p>Here’s an example using Poetry (other tools are similar).</p><h3>4.1 Add a GitHub dependency in pyproject.toml</h3><pre>[tool.poetry.dependencies]<br>python = &quot;^3.11&quot;</pre><pre>device-protocol = { git = &quot;https://github.com/your-org/device-protocol.git&quot;, tag = &quot;v0.1.0&quot; }</pre><p>This tells Poetry to:</p><ul><li>Pull the code from the given GitHub repo</li><li>Use the code at tag v0.1.0</li><li>Install it as a normal Python package</li></ul><p>Then you install / update it like any other dependency:</p><pre>poetry install<br># or<br>poetry update device-protocol</pre><p>If you’re using raw pip, it looks like this:</p><pre>pip install &quot;device-protocol @ git+https://github.com/your-org/device-protocol.git@v0.1.0&quot;</pre><h3>4.2 Using the client in the main app</h3><p>Now the main app can just do something like (conceptual example, not real code):</p><pre>from device_protocol.client import DeviceClient<br><br>client = DeviceClient(<br>    serial_port=&quot;/dev/ttyS0&quot;,<br>    baudrate=19200,<br>)<br>status = client.get_status()<br>client.unlock(door_id=1)</pre><p>The service only cares about <strong>what</strong> it wants to do: unlock, check status, configure something, etc.</p><p>It no longer needs to:</p><ul><li>Manually build frames</li><li>Compute checksums</li><li>Decode low‑level error codes</li></ul><p>That separation — business logic on top, protocol logic underneath — makes the code significantly easier to read and reason about.</p><h3>5. Versioning and tags: keeping things reproducible</h3><p>Since the main apps depend on a Git tag, a consistent release process is important.</p><p>My simple workflow:</p><ol><li>Make changes in the library repo and update tests</li><li>Bump the version in pyproject.toml (say, to 0.2.0)</li><li>Commit &amp; push</li><li>Tag the release:</li></ol><pre>git tag v0.2.0 git push origin v0.2.0</pre><ol><li>Update the main project’s pyproject.toml to use v0.2.0</li><li>Run CI / tests and verify everything still behaves correctly</li></ol><p>This has a few benefits:</p><ul><li><strong>Each app clearly documents which library version it used</strong><br>Six months later, we can still reproduce that setup.</li><li><strong>Rollback is straightforward</strong><br>Change the tag back to the previous version, reinstall, and you’re done.</li><li><strong>Breaking changes are explicit</strong><br>If we change the protocol behavior in a significant way, we bump to 1.x.x and communicate that it’s not just a tiny patch.</li></ul><h3>6. Practical benefits we actually felt</h3><p>After extracting the communication logic into a custom package, a few improvements were immediately noticeable.</p><h3>6.1 No more “copy &amp; paste the old file”</h3><p>Before this, adding a new service that talked to the device usually meant copying a bunch of files from some existing project and editing them.</p><p>Over time that produced four or five slightly different versions of “almost the same protocol code.” Fixing one bug meant hunting for every place that might contain a copy.</p><p>Now a new service just needs:</p><pre>device-protocol = { git = &quot;...&quot;, tag = &quot;v0.2.0&quot; }</pre><p>And then it follows the documented API.<br>Maintenance cost dropped a lot.</p><h3>6.2 Refactoring the protocol feels much safer</h3><p>Sometimes we realize the protocol behavior could be better — maybe timeouts are too aggressive, or error handling is messy.</p><p>Previously, any change came with a nervous thought:</p><blockquote><em>“If I tweak this, which services am I going to break…?”</em></blockquote><p>With a dedicated library:</p><ol><li>We design the new behavior properly</li><li>Write / update tests in the library</li><li>Release a new version</li><li>Upgrade services <strong>one by one, deliberately</strong></li></ol><p>Each service chooses when to upgrade and can test in its own staging environment first. No more “all‑or‑nothing” upgrades.</p><h3>6.3 Onboarding new teammates is easier</h3><p>Before, explaining the protocol implementation meant opening multiple files spread across the app and scrolling around while talking:</p><blockquote><em>“This part is the parser, that part is the frame builder, and over here is some error handling…”</em></blockquote><p>Now I just say:</p><blockquote><em>“All protocol logic lives in a separate library called </em><em>device-protocol.<br>It has a README and tests. Start there.”</em></blockquote><p>Concentrating complexity in one place gives the team a shared reference point and a common vocabulary when discussing changes.</p><h3>7. A few bumps along the way</h3><p>It wasn’t all smooth sailing. A couple of things were worth noting.</p><ol><li><strong>I over‑abstracted at the beginning</strong><br>At first I wanted everything to be extremely generic and future‑proof.<br>The result was code that even I didn’t enjoy reading.<br>I ended up rolling it back and made it faithfully reflect our current usage first.<br>Once the second and third devices show up, then we can generalize.</li><li><strong>Skipping tests made the extraction scary</strong><br>My first instinct was “just move the code out and see.”<br>Halfway through I started wondering, “Did I subtly change any behavior?”<br>After I added proper tests, the anxiety dropped a lot.</li><li><strong>Boundaries needed clear decisions</strong><br>Questions like:</li></ol><ul><li>How much logging belongs inside the library?</li><li>Should the library raise custom exceptions and let callers decide what to do?</li><li>Who owns retry logic — the library or the app?</li></ul><ol><li>Without clear answers, the library starts absorbing business logic again, which is exactly what I wanted to avoid.</li></ol><h3>8. Notes to my future self</h3><p>Since I know I’ll forget some of this over time, here are a few reminders (which might be useful to you too):</p><ul><li><strong>If some code “feels like a library,” start by reshaping the directory structure</strong><br>You don’t have to publish it right away. Just drawing the boundary often clarifies your design.</li><li><strong>Tests are your safety net for extraction</strong><br>Lock in existing behavior with tests before refactoring aggressively.</li><li><strong>Treat internal libraries like real products</strong><br>Even if only your company uses them, versioning and tags are worth doing properly.</li><li><strong>Docs don’t need to be fancy; they just need to help “future you”</strong><br>At minimum, write down:</li><li>What problem this library solves</li><li>The most common usage examples</li><li>Any gotchas people should know before using it</li></ul><h3>Closing thoughts</h3><p>Taking something as low‑level as device communication and turning it into a clean, reusable Python package felt more than just a refactor. It was a chance to rethink how we organize our code — and our mental model.</p><p>It reminded me that:</p><blockquote><em>Whenever a piece of code keeps reappearing in different places,<br>maybe it deserves to be treated as a proper library.</em></blockquote><p>If your team also has a “hidden universe” like this — <br>a big chunk of logic that everyone copies but nobody owns — <br>starting with a small, focused internal package might be a surprisingly effective way to clean things up.</p><p>And if you’ve gone through a similar extraction / packaging story, I’d love to hear how you approached it. Maybe we can steal a few ideas from each other.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=916f3805d163" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/turning-an-internal-communication-module-into-a-custom-python-package-916f3805d163">Turning an Internal Communication Module into a Custom Python Package</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pydantic TypeAdapter: Supercharging Plain Python Types]]></title>
            <link>https://medium.com/codecodecode/pydantic-typeadapter-supercharging-plain-python-types-d952623829c3?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d952623829c3</guid>
            <category><![CDATA[pydanticv2]]></category>
            <category><![CDATA[pydantic]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Thu, 13 Nov 2025 18:51:56 GMT</pubDate>
            <atom:updated>2025-11-13T18:51:56.039Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>TL;DR:</em></strong><em> The core purpose of </em><em>TypeAdapter is to give </em>any Python type<em> the same superpowers as a </em><em>BaseModel: validation, serialization, and JSON Schema generation — without forcing you to create a model class.</em></blockquote><p>If you’ve used Pydantic v2 for a while, you’ve probably asked yourself:</p><blockquote>“I already have BaseModel. Why do I need TypeAdapter?”</blockquote><p>This article answers that question with clear explanations, real examples, and practical scenarios.<br>Spoiler: TypeAdapter fixes a deep pain point —</p><blockquote><strong><em>“What if what I want to validate </em>is not<em> a model class, but a </em>type expression<em>?”</em></strong></blockquote><h3>1. What exactly is a TypeAdapter?</h3><p>The official docs say:</p><blockquote>Type adapters provide a flexible way to perform validation and serialization based on a Python type.<em> </em></blockquote><ul><li>You give TypeAdapter a Python type annotation —<br>e.g. list[int], dict[str, int], list[User], Annotated[int, Field(gt=0)], Union[Cat, Dog]…</li><li>It returns an object that knows how to:</li><li>validate_python(...)</li><li>validate_json(...) citeturn0search1</li><li>dump_python(...)</li><li>dump_json(...) (<strong>returns bytes</strong>) citeturn0search1turn0search6</li><li>json_schema(...) (replaces the old schema_of) citeturn0search5</li></ul><p>In Pydantic v1, only BaseModel could do this.<br>TypeAdapter in v2 extracts this power so <strong>any compatible type</strong> can use it.</p><h3>2. Why isn’t BaseModel enough?</h3><h3>The fundamental purpose of TypeAdapter</h3><p>Think of these common situations:</p><ol><li>You want to validate a plain list[int].<br>Should you really create a wrapper model like this?</li></ol><pre>class IntListWrapper(BaseModel):    <br>   items: list[int]</pre><p>2. You have a TypedDict or dataclass and want to validate a list[ThatType].</p><p>3. You want simple function-level validation without creating dozens of tiny BaseModels.</p><p>4. You’re building a library or SDK and need type-safe boundaries.</p><p>All these scenarios share one thing:</p><blockquote><strong><em>You want to validate a </em>type expression<em>, not an instance of a model class.</em></strong></blockquote><p>That’s exactly the use case TypeAdapter solves.</p><p>Put simply:</p><ul><li><strong>BaseModel is class‑centric.</strong></li><li><strong>TypeAdapter is type‑centric.</strong></li></ul><h3>3. Minimal Examples: Learn TypeAdapter in 3 Lines</h3><h3>Example 1: Validate list[int]</h3><pre>from pydantic import TypeAdapter<br><br>adapter = TypeAdapter(list[int])<br>result = adapter.validate_python([&quot;1&quot;, 2, 3])<br>print(result)  # [1, 2, 3]</pre><p>Pydantic converts &quot;1&quot; → 1 automatically.</p><h3>Example 2: Validate list[TypedDict] (from official docs) citeturn0search1</h3><pre>from typing_extensions import TypedDict<br>from pydantic import TypeAdapter, ValidationError<br><br>class User(TypedDict):<br>    name: str<br>    id: int<br><br>adapter = TypeAdapter(list[User])<br>users = adapter.validate_python([{&quot;name&quot;: &quot;Fred&quot;, &quot;id&quot;: &quot;3&quot;}])<br>print(users)<br># [{&#39;name&#39;: &#39;Fred&#39;, &#39;id&#39;: 3}]<br><br>try:<br>    adapter.validate_python([{&quot;name&quot;: &quot;Fred&quot;, &quot;id&quot;: &quot;oops&quot;, &quot;extra&quot;: &quot;ignored&quot;}])<br>except ValidationError as e:<br>    print(e)</pre><h3>Example 3: Validate an Annotated type with constraints</h3><pre>from typing import Annotated<br>from pydantic import Field, TypeAdapter, ValidationError<br><br>PositiveInt = Annotated[int, Field(gt=0)]<br>adapter = TypeAdapter(PositiveInt)<br>print(adapter.validate_python(5))<br><br>try:<br>    adapter.validate_python(-1)<br>except ValidationError as exc:<br>    print(exc)</pre><p>This pattern keeps constraints reusable and beautiful.</p><h3>4. When to use BaseModel vs TypeAdapter?</h3><h3>Use BaseModel when:</h3><ul><li>The structure is stable (User, Item, Order…)</li><li>You want:</li><li>default values</li><li>methods on the model</li><li>ORM integration</li><li>model_validate() and model_dump()</li></ul><h3>Use TypeAdapter when:</h3><ul><li>What you want to validate is a <strong>type</strong>, not a class:</li></ul><blockquote>list[Model]</blockquote><blockquote>Union[Cat, Dog]</blockquote><blockquote>dict[str, list[int]]</blockquote><blockquote>Annotated types</blockquote><ul><li>You don’t want to create “wrapper models”</li><li>You want elegant function-level validation</li><li>You’re building an SDK and need a strong boundary</li></ul><h3>5. Real‑World Scenarios Where TypeAdapter Shines</h3><h3>Scenario A — Validate API responses (list of models)</h3><pre>from typing import List<br>from pydantic import BaseModel, TypeAdapter<br><br>class Item(BaseModel):<br>    id: int<br>    name: str<br>raw = [<br>    {&quot;id&quot;: 1, &quot;name&quot;: &quot;A&quot;},<br>    {&quot;id&quot;: &quot;2&quot;, &quot;name&quot;: &quot;B&quot;},<br>]<br>adapter = TypeAdapter(List[Item])<br>items = adapter.validate_python(raw)<br>print(items)</pre><p>This avoids looping over elements manually.</p><h3>Scenario B — Function‑level validation</h3><pre>from typing import Annotated<br>from pydantic import TypeAdapter, Field<br><br>UserId = Annotated[int, Field(gt=0)]<br>user_id_adapter = TypeAdapter(UserId)<br>def load_user(uid_raw):<br>    uid = user_id_adapter.validate_python(uid_raw)<br>    print(&quot;Loading user&quot;, uid)</pre><p>No need to create LoadUserRequestModel.</p><h3>Scenario C — Build SDKs / libraries with type‑safe boundaries</h3><pre>from typing_extensions import TypedDict<br>from typing import List<br>from pydantic import TypeAdapter, ValidationError<br><br>class Task(TypedDict):<br>    id: int<br>    name: str<br><br>adapter = TypeAdapter(List[Task])<br><br>class InvalidTaskList(Exception):<br>    pass<br>def process_tasks(raw):<br>    try:<br>        return adapter.validate_python(raw)<br>    except ValidationError as e:<br>        raise InvalidTaskList(str(e)) from e</pre><p>This ensures all inputs entering your SDK are clean.</p><h3>Scenario D — Generate JSON Schema from any type</h3><pre>from pydantic import TypeAdapter<br><br>schema = TypeAdapter(list[int]).json_schema()<br>print(schema)</pre><p>Useful for:</p><ul><li>front‑end form validation</li><li>OpenAPI extensions</li><li>static schema validation</li></ul><h3>6. Important Details &amp; Traps</h3><h3>1. dump_json returns bytes</h3><p>Not a string. This is intentional.citeturn0search1turn0search6</p><pre>json_bytes = adapter.dump_json(data)<br>json_str = json_bytes.decode(&quot;utf-8&quot;)</pre><h3>2. A TypeAdapter is not a type</h3><p>You must NOT use it as a field annotation. Official warning: citeturn0search0turn0search3</p><p>❌ Wrong:</p><pre>class X(BaseModel):<br>    data: TypeAdapter(list[int])</pre><p>✔ Correct:</p><pre>class X(BaseModel):<br>    data: list[int]</pre><h3>3. Reuse adapters for performance</h3><p>Creating a TypeAdapter triggers schema construction — reuse them at module level when possible. citeturn0search1turn0search5</p><h3>7. Practical Architecture Advice</h3><p>A clean Pydantic v2 project often has:</p><h3>1. types.py — reusable Annotated types</h3><pre>UserId = Annotated[int, Field(gt=0)]<br>EmailList = list[Annotated[str, Field(pattern=&quot;.+@.+&quot;)]]</pre><h3>2. adapters.py — shared TypeAdapters</h3><pre>user_id_adapter = TypeAdapter(UserId)<br>email_list_adapter = TypeAdapter(EmailList)</pre><h3>3. BaseModel for domain models</h3><pre>class User(BaseModel):<br>    id: UserId<br>    name: str</pre><p>Combined together, this creates a project that is:</p><ul><li>type‑centric</li><li>easy to test</li><li>easy to scale</li><li>extremely expressive</li></ul><h3>8. Conclusion: Making Types First‑Class Citizens</h3><p>TypeAdapter exists because real‑world data isn’t always a single model — it’s often:</p><ul><li>a nested list</li><li>a dict of lists</li><li>a union of multiple shapes</li><li>or a structure defined by Annotated and constraints</li></ul><p>TypeAdapter elevates these <em>type expressions</em> into powerful reusable validators.</p><p>Think of it like this:</p><blockquote><strong><em>BaseModel gives structure personality.<br>TypeAdapter gives types superpowers.</em></strong></blockquote><p>Whenever you’re tempted to create a tiny wrapper model just to validate something like list[User], try this instead:</p><pre>items = TypeAdapter(list[User]).validate_python(raw)</pre><p>You may suddenly realize:<br><strong>This is exactly what was missing in Pydantic v1.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d952623829c3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/pydantic-typeadapter-supercharging-plain-python-types-d952623829c3">Pydantic TypeAdapter: Supercharging Plain Python Types</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Uvicorn vs Gunicorn: It’s Not a Fight, It’s About Who Owns the Responsibility]]></title>
            <link>https://medium.com/codecodecode/uvicorn-vs-gunicorn-its-not-a-fight-it-s-about-who-owns-the-responsibility-51eb6f7827aa?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/51eb6f7827aa</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gunicorn]]></category>
            <category><![CDATA[uvicorn]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 17:47:56 GMT</pubDate>
            <atom:updated>2025-11-06T17:47:56.451Z</atom:updated>
            <content:encoded><![CDATA[<p>Every time we talk about deploying Python web services, the same question shows up:</p><blockquote><em>“Should I use Uvicorn or Gunicorn for production?”</em></blockquote><p>Most answers online stay at: “This one is faster”, “That one is more popular”, “Use both”.<br>Useful, but incomplete.</p><p>If you’re building real systems — APIs, async services, WebSocket backends, containerized apps — the better question is:</p><blockquote><strong><em>In your architecture, who is responsible for process management, resilience, and scaling?</em></strong><em><br>Is it your application server (Gunicorn)? Or your platform (Kubernetes, systemd, ECS, Nomad, etc.)?</em></blockquote><p>Once you’re clear on that, choosing between Uvicorn, Gunicorn, or both becomes much easier.</p><p>This article walks through: — where they came from, — what problems they were built to solve, — how they evolved, — how they’re used in real deployments, — and how to choose them intentionally.</p><p>No benchmarks flexing, no framework fanboyism — just practical context.</p><h3>1. Origins: What Problem Was Each Trying to Solve?</h3><h3>Gunicorn: The WSGI-Era Workhorse</h3><p>Before asyncio and modern async frameworks, the Python web world was dominated by synchronous frameworks:</p><ul><li>Django</li><li>Flask</li><li>Pyramid</li><li>etc.</li></ul><p>The pain points back then were straightforward:</p><ul><li>A single Python process can’t fully utilize multi-core CPUs.</li><li>If that one process dies, your whole app dies with it.</li><li>People needed:</li><li>a master process to supervise worker processes,</li><li>predictable behavior under load,</li><li>timeouts, graceful reloads, logging,</li><li>a unified way to run different WSGI apps behind Nginx or another proxy.</li></ul><p><strong>Gunicorn (Green Unicorn)</strong> stepped in as:</p><ul><li>a production-grade <strong>WSGI HTTP server</strong>,</li><li>built on a <strong>pre-fork master/worker model</strong>,</li><li>focused on stability, robustness, and simplicity.</li></ul><p>In short:</p><blockquote><strong><em>Gunicorn’s primary purpose is process management and stable request handling for WSGI apps.</em></strong><em><br>Async, WebSockets, HTTP/2 were not its original concerns.</em></blockquote><h3>Uvicorn: The ASGI-Native Sprinter</h3><p>Then Python gained asyncio. New frameworks appeared:</p><ul><li>Starlette</li><li>FastAPI</li><li>Django Channels and friends</li></ul><p>These needed more than WSGI:</p><ul><li>native async/await support,</li><li>long-lived connections (WebSocket, SSE),</li><li>modern protocols (HTTP/2),</li><li>the ability to mix sync and async cleanly.</li></ul><p>That’s where <strong>ASGI (Asynchronous Server Gateway Interface)</strong> comes in — a new standard designed for both sync and async applications.</p><p><strong>Uvicorn</strong> was built as:</p><ul><li>a <strong>lightweight, high-performance ASGI server</strong>,</li><li>powered by tools like uvloop and httptools,</li><li>with first-class support for:</li><li>async I/O,</li><li>WebSockets,</li><li>modern connection handling.</li></ul><p>In one line:</p><blockquote><strong><em>Uvicorn’s job is to efficiently run ASGI apps. It doesn’t try to be a heavyweight process supervisor.</em></strong></blockquote><h3>2. Design Philosophy: Who Does What?</h3><h3>Gunicorn: “I’ll Take Care of the Workers”</h3><p>Gunicorn’s philosophy:</p><ul><li>You give me a compliant app (WSGI, or ASGI via a worker class),</li><li>I’ll take care of:</li><li>forking workers,</li><li>restarting crashed workers,</li><li>enforcing timeouts,</li><li>graceful reloads,</li><li>limiting memory usage with max-requests,</li><li>logging across workers.</li></ul><p>In the pre-container era — or single-VM setups — <strong>Gunicorn was the de facto choice</strong> for running Python web apps in production. It acted as the “mini platform” around your app.</p><h3>Uvicorn: “I’ll Run Fast, You Decide How to Supervise Me”</h3><p>Uvicorn’s approach is different:</p><ul><li>be fast,</li><li>be simple,</li><li>be a great ASGI runtime,</li><li>expose the basics:</li><li>workers,</li><li>logging,</li><li>proxy header support.</li></ul><p>It does <strong>not</strong> try to replace Kubernetes, systemd, or any orchestration layer.</p><p>In a modern setup, that’s perfect:</p><blockquote><em>Let your infrastructure handle restarts, scaling, and health checks.<br>Let Uvicorn focus on handling requests efficiently.</em></blockquote><h3>3. Why “Gunicorn + UvicornWorker” Exists</h3><p>As ASGI frameworks grew, many teams had the same thought:</p><blockquote><em>“We already know and trust Gunicorn. Can we keep using it and still run ASGI apps properly?”</em></blockquote><p>Yes. That’s where this classic combo comes in:</p><pre>gunicorn app.main:app \<br>  -k uvicorn.workers.UvicornWorker \<br>  -w 4 -b 0.0.0.0:8000</pre><p>What this setup means:</p><ul><li><strong>Gunicorn</strong>:</li><li>stays the master process,</li><li>manages workers, timeouts, restarts, reloads.</li><li><strong>Uvicorn</strong>:</li><li>runs inside each worker,</li><li>provides the ASGI runtime,</li><li>handles async I/O, WebSockets, etc.</li></ul><p>So it’s not “Uvicorn vs Gunicorn”. It’s:</p><blockquote><em>Use </em><strong><em>Gunicorn for supervision</em></strong><em>,<br>Use </em><strong><em>Uvicorn as the ASGI engine</em></strong><em>.</em></blockquote><p>At the same time, containerization changed the game:</p><ul><li>With Docker and Kubernetes, you often <strong>don’t need Gunicorn</strong> as a separate process manager.</li><li>Each container runs one Uvicorn process (with a small number of workers),</li><li>and the platform (K8s, ECS, Nomad, etc.) takes care of:</li><li>restarting,</li><li>rolling updates,</li><li>scaling out.</li></ul><p>Both models are valid. Which one you choose depends on where you put responsibility.</p><h3>4. Real-World Scenarios: How to Choose in Practice</h3><p>Let’s ground this in concrete deployment patterns.</p><h3>Scenario 1: FastAPI + Docker + Kubernetes (Cloud-Native)</h3><p><strong>Recommended: Uvicorn directly.</strong></p><p>Example:</p><pre>uvicorn app.main:app \<br>  --host 0.0.0.0 --port 8000 \<br>  --workers 2</pre><p>Why this setup works well:</p><ul><li>Each Pod runs a simple Uvicorn-based service.</li><li>Scaling is done via replicas / HPA at the orchestration layer.</li><li>Health checks, restarts, rollouts: handled by Kubernetes.</li><li>WebSockets, async I/O, modern protocols: handled by Uvicorn/ASGI.</li></ul><p>In this world, adding Gunicorn on top often just adds complexity.</p><h3>Scenario 2: Single Linux VM / Bare Metal, No Orchestrator</h3><p><strong>Recommended: Gunicorn + UvicornWorker (for ASGI)<br>or plain Gunicorn (for WSGI).</strong></p><p>Example for ASGI (FastAPI, Starlette):</p><pre>gunicorn app.main:app \<br>  -k uvicorn.workers.UvicornWorker \<br>  -w 4 -b 0.0.0.0:8000 \<br>  --timeout 60 \<br>  --max-requests 2000 --max-requests-jitter 200 \<br>  --access-logfile - --error-logfile -</pre><p>This is a great fit if:</p><ul><li>You don’t have Kubernetes or similar tooling.</li><li>You want:</li><li>worker supervision out of the box,</li><li>predictable timeout behavior,</li><li>graceful reloads,</li><li>basic memory leak mitigation.</li></ul><p>Here, <strong>Gunicorn is effectively your lightweight platform</strong>, and Uvicorn plugs into it as the ASGI executor.</p><h3>Scenario 3: Local Development, Side Projects, Small Internal Tools</h3><p><strong>Recommended: Uvicorn alone.</strong></p><p>Example:</p><pre>uvicorn app.main:app --reload</pre><p>Reasons:</p><ul><li>Fast to install.</li><li>Great DX with --reload.</li><li>Keeps your dev and container entrypoint close to what prod uses.</li></ul><p>No need to over-engineer just to “look” production-grade.</p><h3>Scenario 4: WebSockets, SSE, Long-Lived Connections</h3><p>If you have real-time or streaming needs:</p><ul><li>You <strong>must</strong> use an ASGI server.</li><li>Valid options:</li><li>Uvicorn alone,</li><li>or Gunicorn + UvicornWorker.</li></ul><p>Avoid relying purely on Gunicorn’s sync workers here.<br>They weren’t designed for long-lived async connections.</p><h3>5. Deep-Dive Comparison: Dimension by Dimension</h3><h3>Protocol &amp; Ecosystem</h3><ul><li><strong>Gunicorn</strong></li><li>Native: WSGI.</li><li>Extensions: ASGI via worker classes likeuvicorn.workers.UvicornWorker.</li><li>Great for Django/Flask classic stacks.</li><li><strong>Uvicorn</strong></li><li>Native: ASGI.</li><li>Ideal for FastAPI, Starlette, modern async stacks.</li></ul><h3>Role &amp; Responsibility</h3><ul><li><strong>Gunicorn</strong></li><li>Master/manager:</li><li>forks workers,</li><li>supervises,</li><li>handles reloads, timeouts, restarts.</li><li><strong>Uvicorn</strong></li><li>Runtime:</li><li>runs your ASGI app efficiently,</li><li>expects something else (if needed) to manage processes at a higher level.</li></ul><h3>Multi-Core Utilization</h3><ul><li><strong>Gunicorn</strong></li><li>Built for it: -w controls worker count.</li><li>--max-requests helps recycle workers and mitigate leaks.</li><li><strong>Uvicorn</strong></li><li>Supports --workers, but intentionally lightweight.</li><li>In containerized setups, multi-core usage usually comes from:</li><li>multiple workers per container, <strong>and / or</strong></li><li>multiple containers.</li></ul><h3>Platform Compatibility</h3><ul><li><strong>Gunicorn</strong></li><li>Unix-like only (Linux, macOS).</li><li>Not for Windows.</li><li><strong>Uvicorn</strong></li><li>Cross-platform: Linux, macOS, Windows.</li><li>Makes it easy to have a similar CLI for both dev and prod.</li></ul><h3>Ops &amp; Tuning Experience</h3><ul><li><strong>Gunicorn</strong></li><li>Rich, battle-tested options:</li><li>timeouts,</li><li>logging,</li><li>reload strategies,</li><li>worker types.</li><li>Natural fit for traditional ops teams.</li><li><strong>Uvicorn</strong></li><li>Clean and minimal:</li><li>great fit for Docker + orchestration,</li><li>fewer knobs at the process-management layer,</li><li>expects the platform to do more of the heavy lifting.</li></ul><h3>6. Practical Decision Rules</h3><p>You don’t need a matrix. A few clear rules go a long way:</p><ol><li><strong>Using FastAPI / Starlette in Docker/Kubernetes?</strong></li></ol><ul><li>Run <strong>Uvicorn directly</strong>.</li><li>Let the platform own scaling, health, and restarts.</li></ul><p><strong>2. Running on a single VM / bare metal without orchestration?</strong></p><ul><li>Use <strong>Gunicorn</strong>.</li><li>For WSGI apps: Gunicorn alone.</li><li>For ASGI apps: <strong>Gunicorn + </strong><strong>UvicornWorker</strong>.</li><li>Let Gunicorn be your mini process manager.</li></ul><p><strong>3. Need WebSockets / SSE / long-lived connections?</strong></p><ul><li>Use Uvicorn (alone or via UvicornWorker).</li><li>Don’t rely on pure sync workers for this.</li></ul><p><strong>4. Already have a strong supervisor (systemd, ECS, Nomad, K8s, etc.)?</strong></p><ul><li>Treat Gunicorn as optional.</li><li>A lean stack with <strong>“Infra + Uvicorn”</strong> is often cleaner and easier to reason about.</li></ul><h3>7. Conclusion: It’s About Ownership, Not Hype</h3><p>Summing it up:</p><ul><li><strong>Gunicorn</strong></li><li>Born in the WSGI era.</li><li>Excellent at:</li><li>multi-process management,</li><li>stability,</li><li>predictable behavior on a single host.</li><li>Great when you <em>don’t</em> already have a sophisticated orchestration layer.</li><li><strong>Uvicorn</strong></li><li>Born in the ASGI era.</li><li>Excellent at:</li><li>async-native performance,</li><li>WebSockets and modern protocols,</li><li>fitting naturally into containerized, cloud-native environments.</li></ul><p>They’re not enemies.</p><ul><li>Want Gunicorn’s operational maturity <strong>and</strong> Uvicorn’s async runtime?</li><li>Use <strong>Gunicorn + </strong><strong>UvicornWorker</strong>.</li><li>Already invested in Kubernetes / ECS / Nomad / systemd with solid health checks and autoscaling?</li><li>Run <strong>Uvicorn directly</strong>, keep the stack simple.</li></ul><p>The real question isn’t:</p><blockquote><em>“Which one is more popular?”</em></blockquote><p>It’s:</p><blockquote><strong><em>“In my architecture, who is responsible for process lifecycle, resilience, and scaling — the app server, or the platform?”</em></strong></blockquote><p>Answer that honestly, and your choice between Uvicorn and Gunicorn almost picks itself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=51eb6f7827aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/uvicorn-vs-gunicorn-its-not-a-fight-it-s-about-who-owns-the-responsibility-51eb6f7827aa">Uvicorn vs Gunicorn: It’s Not a Fight, It’s About Who Owns the Responsibility</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Trusting /dev/ttyUSB0: Using udev Rules for Stable Device Naming on Linux]]></title>
            <link>https://medium.com/codecodecode/stop-trusting-dev-ttyusb0-using-udev-rules-for-stable-device-naming-on-linux-adc878f19ee9?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc878f19ee9</guid>
            <category><![CDATA[iot]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[udev]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Thu, 06 Nov 2025 17:27:54 GMT</pubDate>
            <atom:updated>2025-11-06T17:27:54.921Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve ever worked with USB serial adapters, barcode or QR scanners, card readers, industrial controllers, LTE modems, cameras, or other USB toys on Linux, you’ve probably seen this happen:</p><blockquote><em>Everything worked yesterday on </em><em>/dev/ttyUSB0.<br>Today it’s </em><em>/dev/ttyUSB1. Nothing works. You stare at the screen in quiet regret.</em></blockquote><p>This is one of those problems that feels random and cursed until you realize: it’s not a bug, it’s how Linux device naming works.</p><p>In this article we’ll walk through, in plain language:</p><ul><li>Why device names like /dev/ttyUSB0 are unstable</li><li>Common “quick fixes” people use (and why they fall apart)</li><li>Why serious systems end up using <strong>udev device rules</strong></li><li>How to write safe, readable udev rules</li><li>Practical examples you can drop into real projects</li></ul><p>The goal: give your hardware a stable identity, instead of hoping the kernel feels the same way about /dev/ttyUSB0 tomorrow.</p><h3>1. The core problem: /dev/* names are not a promise</h3><p>On Linux, physical devices are exposed as nodes under /dev, for example:</p><ul><li>/dev/ttyUSB0, /dev/ttyUSB1</li><li>/dev/ttyACM0</li><li>/dev/input/event0, event1</li><li>/dev/sda, /dev/sdb</li><li>/dev/video0, /dev/video1</li></ul><p>Here’s the important part:</p><p><strong>Many of these names are based on detection order, not on “which exact device” you plugged in.</strong></p><p>Some very real scenarios:</p><ul><li>You add a second USB-serial adapter. Now your “main” adapter becomes ttyUSB1 instead of ttyUSB0.</li><li>Boot timing changes after a kernel update. Devices appear in a different order.</li><li>Someone moves a cable to a different USB port. The mapping shifts.</li><li>A hub gets added in the middle. Paths and ordering change.</li></ul><p>If your code, Docker config, or systemd units say:</p><pre>/dev/ttyUSB0<br>/dev/input/event0<br>/dev/video0</pre><p>you are basically asking for trouble in any non-trivial environment. It might work on your laptop. It will eventually break in production.</p><p>The kernel’s job is: “here’s a node for each device”.<br>It does <strong>not</strong> promise: “this node is always your favorite USB dongle”.</p><h3>2. Popular but fragile ways people try to cope</h3><p>Before we get to udev rules, let’s look at the usual strategies and their trade-offs.</p><h3>2.1 Hard-coding /dev/ttyUSB0</h3><p>The classic.</p><p>It’s… fine for:</p><ul><li>a quick demo,</li><li>a single box on your desk,</li><li>one device, never changing.</li></ul><p>The moment you:</p><ul><li>plug in another similar device,</li><li>move to a different machine,</li><li>change the setup,</li></ul><p>your assumption collapses.</p><h3>2.2 Using /dev/serial/by-path/ (based on physical port)</h3><p>by-path gives you device names based on the hardware path, e.g.:</p><pre>/dev/serial/by-path/pci-0000:00:14.0-usb-0:1.2:1.0-port0</pre><p><strong>Pros:</strong></p><ul><li>Stable as long as the device stays on that exact port.</li><li>Nice for embedded systems or racked machines where ports are fixed.</li></ul><p><strong>Cons:</strong></p><ul><li>Move the cable → different path.</li><li>Add a USB hub or change the topology → different path.</li><li>Not very friendly for humans reading configs.</li></ul><p>Good when: <strong>you fully control cabling and nobody randomly unplugs things.</strong></p><h3>2.3 Using /dev/serial/by-id/ (based on device identity)</h3><p>by-id uses properties like vendor, product, and serial to create more stable names:</p><pre>/dev/serial/by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller_D_CFAVb115818-if00-port0</pre><p><strong>Pros:</strong></p><ul><li>Much more stable: reboots and port changes are usually fine.</li><li>Often “just works” without extra configuration.</li></ul><p><strong>Cons:</strong></p><ul><li>Some devices have no real serial number. Some cheap clones share the same fake one.</li><li>Names can be extremely long.</li><li>You may still want custom permissions, groups, or higher-level names.</li></ul><p>This is where <strong>udev rules</strong> come in: we can take those properties and define our own clean, meaningful, and stable names.</p><h3>3. Why udev device rules?</h3><p>udev is the user-space device manager on Linux. It listens for device events and applies rules that can:</p><ul><li>Set permissions and ownership</li><li>Add environment variables</li><li>Attach tags for other services</li><li>And, importantly: <strong>create human-friendly symlinks</strong></li></ul><p>The key idea:</p><blockquote><em>Use the device’s identity (vendor, product, serial, etc.) to create a stable name, instead of relying on “whichever device came first”.</em></blockquote><p>This lets you define things like:</p><ul><li>/dev/ttyMainController → that specific RS-485 adapter</li><li>/dev/input/qrscanner → that specific QR scanner</li><li>/dev/video/frontdoor → that specific camera</li></ul><p>Once that exists, everything else becomes simpler:</p><ul><li>Applications always open /dev/ttyMainController.</li><li>Docker containers bind the same path every time.</li><li>systemd units can explicitly depend on a known device name.</li><li>Documentation becomes readable: “Check /dev/ttyMainController exists” is a lot nicer than “Hope it’s still ttyUSB0”.</li></ul><h3>4. How to write good udev rules (without shooting yourself in the foot)</h3><h3>4.1 First step: inspect your device with udevadm</h3><p>Pick the existing device node (e.g. /dev/ttyUSB0) and run:</p><pre>udevadm info -a -n /dev/ttyUSB0<br># or<br>udevadm info -a -p &quot;$(udevadm info -q path -n /dev/ttyUSB0)&quot;</pre><p>Look for fields like:</p><ul><li>ATTRS{idVendor}</li><li>ATTRS{idProduct}</li><li>ATTRS{serial}</li><li>ATTRS{manufacturer}</li><li>ATTRS{product}</li><li>SUBSYSTEM</li></ul><p><strong>Good practice:</strong></p><ul><li>Always match at least on idVendor + idProduct.</li><li>Add serial when possible to guarantee uniqueness.</li><li>Avoid super-generic matches like “any device with ‘USB’ in the name”.</li></ul><p>Be precise enough to match your device and not the entire office.</p><h3>4.2 Create a readable, stable symlink</h3><p>Create a rule file, for example:</p><pre>sudo nano /etc/udev/rules.d/99-custom-devices.rules</pre><p>Add something like:</p><pre># USB-Serial adapter → /dev/ttyMyDevice<br>SUBSYSTEM==&quot;tty&quot;, \<br>  ATTRS{idVendor}==&quot;067b&quot;, \<br>  ATTRS{idProduct}==&quot;2303&quot;, \<br>  ATTRS{serial}==&quot;ABCD1234&quot;, \<br>  SYMLINK+=&quot;ttyMyDevice&quot;</pre><p>Reload and trigger:</p><pre>sudo udevadm control --reload-rules<br>sudo udevadm trigger</pre><p>Now you get:</p><ul><li>The actual kernel node (e.g. /dev/ttyUSB0)</li><li>A nice stable symlink: /dev/ttyMyDevice</li></ul><p>Your application uses:</p><pre>import serial<br><br>ser = serial.Serial(&quot;/dev/ttyMyDevice&quot;, baudrate=9600, timeout=1)</pre><p>No more guessing.</p><h3>4.3 Permissions &amp; groups: don’t just spam 0666</h3><p>A lot of examples on the internet look like this:</p><pre>MODE=&quot;0666&quot;</pre><p>Yes, it “fixes” permissions. It also means <strong>everyone</strong> on the machine can read/write that device.</p><p>A safer pattern is:</p><pre>SUBSYSTEM==&quot;tty&quot;, ATTRS{idVendor}==&quot;067b&quot;, ATTRS{idProduct}==&quot;2303&quot;, \<br>  SYMLINK+=&quot;ttyMyDevice&quot;, MODE=&quot;0660&quot;, GROUP=&quot;dialout&quot;</pre><p>Then:</p><pre>sudo usermod -a -G dialout myserviceuser</pre><p>Only specific users (or service accounts) in dialout can touch that device. Same idea applies with input, video, or custom groups.</p><h3>4.4 Working with Docker, Kubernetes, and systemd</h3><p>Important: <strong>udev runs on the host, not inside containers.</strong></p><p>The usual flow:</p><ol><li>Host applies udev rule → creates /dev/ttyMyDevice.</li><li>Container is started with that device mapped in:</li></ol><pre>docker run --rm --device=/dev/ttyMyDevice:/dev/ttyMyDevice my-image:tag</pre><p>3. App inside the container uses /dev/ttyMyDevice.</p><p>For systemd services, you can combine udev tags and device units:</p><pre>[Unit]<br>Description=My Serial Service<br>After=dev-ttyMyDevice.device<br>Requires=dev-ttyMyDevice.device<br><br>[Service]<br>ExecStart=/usr/local/bin/my-service --port /dev/ttyMyDevice<br>Restart=always<br>[Install]<br>WantedBy=multi-user.target</pre><p>Now your service only starts when the right device is actually present.</p><h3>4.5 Handling multiple identical devices</h3><p>If you have multiple adapters of the same model, you still have options.</p><p><strong>Option 1: Different serial numbers → different roles</strong></p><pre>SUBSYSTEM==&quot;tty&quot;, ATTRS{idVendor}==&quot;067b&quot;, ATTRS{idProduct}==&quot;2303&quot;, ATTRS{serial}==&quot;A001&quot;, SYMLINK+=&quot;ttyGateway&quot;<br>SUBSYSTEM==&quot;tty&quot;, ATTRS{idVendor}==&quot;067b&quot;, ATTRS{idProduct}==&quot;2303&quot;, ATTRS{serial}==&quot;A002&quot;, SYMLINK+=&quot;ttyBackup&quot;</pre><p><strong>Option 2: Use port / path intentionally</strong></p><p>If hardware is fixed and port locations have meaning (e.g. left = main, right = backup), you can match using KERNELS / ENV{ID_PATH}.</p><p><strong>Option 3: Generic symlinks + config</strong></p><p>Let udev create stable, descriptive names, and decide mapping (which is “main”) in your app config or environment.</p><h3>5. Practical examples you can reuse</h3><h3>Example 1: RS-485 adapter for an industrial controller</h3><pre># /etc/udev/rules.d/99-serial-rs485.rules<br>SUBSYSTEM==&quot;tty&quot;, \<br>  ATTRS{idVendor}==&quot;1a86&quot;, \<br>  ATTRS{idProduct}==&quot;7523&quot;, \<br>  SYMLINK+=&quot;ttyRS485&quot;, \<br>  MODE=&quot;0660&quot;, GROUP=&quot;dialout&quot;</pre><p>Application:</p><pre>import serial<br>ser = serial.Serial(&quot;/dev/ttyRS485&quot;, 9600)</pre><h3>Example 2: Barcode / QR scanner (HID keyboard style)</h3><p>Many scanners appear as a keyboard input device (/dev/input/eventX).</p><pre># /etc/udev/rules.d/99-barcode-scanner.rules<br>SUBSYSTEM==&quot;input&quot;, \<br>  ATTRS{name}==&quot;MyBarcodeScanner&quot;, \<br>  ENV{ID_INPUT_KEYBOARD}==&quot;1&quot;, \<br>  KERNEL==&quot;event*&quot;, \<br>  SYMLINK+=&quot;input/barcode0&quot;, \<br>  MODE=&quot;0660&quot;, GROUP=&quot;input&quot;</pre><p>Your app can read from /dev/input/barcode0 directly, without mixing with a real keyboard.</p><h3>Example 3: USB camera with a semantic name</h3><pre># /etc/udev/rules.d/99-cameras.rules<br>SUBSYSTEM==&quot;video4linux&quot;, \<br>  ATTRS{idVendor}==&quot;046d&quot;, \<br>  ATTRS{idProduct}==&quot;0825&quot;, \<br>  SYMLINK+=&quot;video/frontdoor&quot;, \<br>  MODE=&quot;0660&quot;, GROUP=&quot;video&quot;</pre><p>Your video stack can always use:</p><pre>/dev/video/frontdoor</pre><p>No more guessing whether video0 is the front door, the back door, or your laptop webcam.</p><h3>6. Final thoughts: make hardware a first-class citizen</h3><p>If your system:</p><ul><li>talks to specific physical devices,</li><li>needs to be reliable across reboots and re-cabling,</li><li>runs anywhere beyond your personal laptop,</li></ul><p>then relying on:</p><pre>/dev/ttyUSB0<br>/dev/input/event0<br>/dev/video0</pre><p>is just asking for intermittent, hard-to-debug failures.</p><p>udev device rules give you:</p><ul><li>Stable names based on real device identity</li><li>Config that can be version-controlled and documented</li><li>Cleaner integration with Docker, Kubernetes, and systemd</li><li>Safer permission handling via groups and modes</li><li>Code and docs that say /dev/ttyMainController instead of “uh, whichever ttyUSB appears first”</li></ul><p>It’s not a fancy trick. It’s basic engineering hygiene for systems that touch the real world.</p><p>If you haven’t done it yet, start simple:</p><ol><li>Pick one critical device.</li><li>Inspect it with udevadm info.</li><li>Give it a clear, stable name via a udev rule.</li><li>Point your app at that new name.</li></ol><p>Future you, and whoever has to keep your system running at 3 a.m., will be very glad you did.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc878f19ee9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/stop-trusting-dev-ttyusb0-using-udev-rules-for-stable-device-naming-on-linux-adc878f19ee9">Stop Trusting /dev/ttyUSB0: Using udev Rules for Stable Device Naming on Linux</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ASGI vs WSGI: A Complete Guide to Their Differences and FastAPI Applications]]></title>
            <link>https://medium.com/codecodecode/asgi-vs-wsgi-a-complete-guide-to-their-differences-and-fastapi-applications-9857f13c4521?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9857f13c4521</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[wsgi]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[asgi]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Wed, 22 Oct 2025 18:10:55 GMT</pubDate>
            <atom:updated>2025-10-22T18:10:55.765Z</atom:updated>
            <content:encoded><![CDATA[<p>In modern Python web development, <strong>WSGI</strong> and <strong>ASGI</strong> are two key server interface standards. Understanding their differences helps developers choose the right framework and deployment approach, optimizing performance and scalability. This article provides a complete explanation of both, focusing on <strong>FastAPI</strong> as a practical example.</p><h3>1. What Is WSGI?</h3><p><strong>WSGI</strong> (Web Server Gateway Interface, PEP 3333) is the traditional Python standard for web applications.</p><p><strong>Key features:</strong> — <strong>Synchronous model (blocking I/O):</strong> Each request runs in a single thread. — <strong>Simple, mature, and stable design.</strong> — Best suited for classic HTTP/1.1 request-response patterns.</p><p>Popular frameworks: <strong>Flask, Django, Bottle</strong>.</p><pre>def simple_wsgi_app(environ, start_response):<br>    start_response(&#39;200 OK&#39;, [(&#39;Content-Type&#39;, &#39;text/plain&#39;)])<br>    return [b&quot;Hello, WSGI!&quot;]</pre><blockquote><em>Best for small REST APIs or apps without real-time or high-concurrency needs.</em></blockquote><h3>2. What Is ASGI?</h3><p><strong>ASGI</strong> (Asynchronous Server Gateway Interface) is the <strong>next-generation asynchronous standard</strong> that evolved from WSGI.</p><p><strong>Key features:</strong> — Supports <strong>async/await</strong> and handles multiple I/O requests concurrently. — Supports multiple protocols: <strong>HTTP/1.1, HTTP/2, WebSocket</strong>. — Built for <strong>high concurrency</strong> and <strong>long-lived connections</strong>.</p><p>Popular frameworks: <strong>FastAPI, Starlette, Django Channels, Litestar</strong>.</p><pre>async def simple_asgi_app(scope, receive, send):<br>    if scope[&#39;type&#39;] == &#39;http&#39;:<br>        await send({<br>            &#39;type&#39;: &#39;http.response.start&#39;,<br>            &#39;status&#39;: 200,<br>            &#39;headers&#39;: [(b&#39;content-type&#39;, b&#39;text/plain&#39;)]<br>        })<br>        await send({<br>            &#39;type&#39;: &#39;http.response.body&#39;,<br>            &#39;body&#39;: b&#39;Hello, ASGI!&#39;<br>        })</pre><blockquote><em>Best for WebSocket, Server-Sent Events (SSE), or highly concurrent REST APIs.</em></blockquote><h3>3. WSGI vs ASGI Comparison</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9aCATwGtdIEX_vTuOyj2Vg.png" /></figure><blockquote><strong><em>In short:</em></strong><em> WSGI is synchronous, while ASGI is event-driven and asynchronous.</em></blockquote><h3>4. FastAPI and ASGI</h3><p>FastAPI is built on <strong>Starlette (ASGI)</strong>, which means: — Full <strong>async/await</strong> support — Handles both HTTP and WebSocket — Allows streaming via StreamingResponse</p><h3>🚀 Example: Async Endpoint in FastAPI</h3><pre>from fastapi import FastAPI<br><br>app = FastAPI()<br>@app.get(&quot;/ping&quot;)<br>async def ping():<br>    return {&quot;message&quot;: &quot;pong&quot;}</pre><p>Run the server: bash uvicorn main:app --reload</p><h3>5. ASGI Middleware Example</h3><p>Unlike WSGI, ASGI middleware is <strong>event-driven</strong> (uses scope, receive, send).</p><pre>import time<br>from starlette.types import ASGIApp, Receive, Scope, Send<br><br>class TimingMiddleware:<br>    def __init__(self, app: ASGIApp):<br>        self.app = app<br>    async def __call__(self, scope: Scope, receive: Receive, send: Send):<br>        if scope[&#39;type&#39;] != &#39;http&#39;:<br>            await self.app(scope, receive, send)<br>            return<br>        start = time.perf_counter()<br>        async def send_wrapper(message):<br>            if message[&#39;type&#39;] == &#39;http.response.start&#39;:<br>                duration = (time.perf_counter() - start) * 1000<br>                message.setdefault(&#39;headers&#39;, []).append(<br>                    (b&#39;x-process-time-ms&#39;, str(duration).encode())<br>                )<br>            await send(message)<br>        await self.app(scope, receive, send_wrapper)</pre><p>Mounting in FastAPI: python app.middleware(&#39;http&#39;)(TimingMiddleware(app))</p><h3>6. Async in Practice</h3><h3>Avoid Blocking Calls</h3><p>Blocking libraries like requests or boto3 freeze the event loop.</p><p><strong>❌ Wrong:</strong></p><pre>import requests <br><br>@app.get(&quot;/data&quot;) <br>async def get_data(): <br>    return requests.get(&quot;https://api.example.com&quot;).json()</pre><p><strong>✅ Correct:</strong></p><pre>import httpx <br><br>@app.get(&quot;/data&quot;) <br>async def get_data(): <br>    async with httpx.AsyncClient() as client: return (await client.get(&quot;https://api.example.com&quot;)).json()</pre><h3>7. Streaming and WebSocket Examples</h3><h3>SSE (Server-Sent Events)</h3><pre>from fastapi.responses import StreamingResponse<br><br>async def sse_generator():<br>    for i in range(3):<br>        yield f&quot;data: event {i}\n\n&quot;<br>@app.get(&quot;/sse&quot;)<br>async def sse_endpoint():<br>    return StreamingResponse(sse_generator(), media_type=&quot;text/event-stream&quot;)</pre><h3>WebSocket Echo</h3><pre>from fastapi import WebSocket, WebSocketDisconnect<br><br>@app.websocket(&quot;/ws&quot;)<br>async def websocket_endpoint(ws: WebSocket):<br>    await ws.accept()<br>    try:<br>        while True:<br>            data = await ws.receive_text()<br>            await ws.send_text(f&quot;Echo: {data}&quot;)<br>    except WebSocketDisconnect:<br>        print(&quot;Client disconnected&quot;)</pre><h3>8. Deployment Options</h3><h3>🔹 Uvicorn (Pure ASGI)</h3><pre>uvicorn app:app --host 0.0.0.0 --port 8000 --workers 4 --loop uvloop --http httptools</pre><h3>🔹 Gunicorn + UvicornWorker (Production)</h3><pre>gunicorn app:app -k uvicorn.workers.UvicornWorker -w 4 -b 0.0.0.0:8000</pre><h3>🔹 Hypercorn (Supports HTTP/2 and HTTP/3)</h3><pre>hypercorn app:app --bind 0.0.0.0:8000 --workers 4</pre><blockquote><em>Tip: Use Nginx as a reverse proxy for TLS, compression, rate limiting, and WebSocket upgrades.</em></blockquote><h3>9. Common Pitfalls and Best Practices</h3><ol><li><strong>Blocking calls:</strong> Use async-compatible clients (httpx.AsyncClient, aioboto3).</li><li><strong>Database connections:</strong> Use SQLAlchemy async engine and manage them in lifespan events.</li><li><strong>WebSocket heartbeat:</strong> Implement ping/pong to prevent memory leaks.</li><li><strong>Streaming responses:</strong> Ensure your proxy (e.g., Nginx) disables buffering.</li><li><strong>Monitoring:</strong> Combine Prometheus, Grafana, and OpenTelemetry to track latency and concurrency.</li></ol><h3>10. When to Use Which?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_vhzL9RmXHse9k2bcSRA5Q.png" /></figure><blockquote><strong><em>Takeaway:</em></strong><em> Use </em><strong><em>ASGI</em></strong><em> for concurrency, streaming, and WebSocket. Stick with </em><strong><em>WSGI</em></strong><em> for simple synchronous workloads.</em></blockquote><h3>11. Further Reading</h3><ul><li><a href="https://peps.python.org/pep-3333/">PEP 3333 — WSGI Specification</a></li><li><a href="https://asgi.readthedocs.io/en/latest/">ASGI Specification</a></li><li><a href="https://fastapi.tiangolo.com/">FastAPI Documentation</a></li><li><a href="https://github.com/encode/uvicorn">Uvicorn GitHub</a></li></ul><h3>Final Thoughts</h3><p>ASGI marks the <strong>asynchronous era</strong> of Python web frameworks. From real-time APIs to IoT control, it enables scalable and efficient systems that handle modern workloads effortlessly.</p><blockquote><em>If you’re modernizing or building new backend services, </em><strong><em>FastAPI + Uvicorn</em></strong><em> is your golden combo for performance and simplicity.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9857f13c4521" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/asgi-vs-wsgi-a-complete-guide-to-their-differences-and-fastapi-applications-9857f13c4521">ASGI vs WSGI: A Complete Guide to Their Differences and FastAPI Applications</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI/Starlette Lifecycle Guide: Startup Order, Pitfalls, Best Practices, and a Production‑Ready…]]></title>
            <link>https://medium.com/codecodecode/fastapi-starlette-lifecycle-guide-startup-order-pitfalls-best-practices-and-a-production-ready-53e29dcb9249?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/53e29dcb9249</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Fri, 17 Oct 2025 19:43:44 GMT</pubDate>
            <atom:updated>2025-10-17T19:43:44.495Z</atom:updated>
            <content:encoded><![CDATA[<h3>FastAPI/Starlette Lifecycle Guide: Startup Order, Pitfalls, Best Practices, and a Production‑Ready Template</h3><blockquote><em>A focused overview of </em><strong><em>FastAPI (on Starlette)</em></strong><em> startup and per‑request lifecycles.</em></blockquote><h3>Why the lifecycle matters</h3><ul><li><strong>Avoid re‑entry &amp; race conditions</strong>: Multiple workers/replicas (e.g., on Kubernetes) re‑run startup. If you trigger DB migrations or warm huge caches during startup, you can easily hit hazards.</li><li><strong>Place heavy resources correctly</strong>: DB/Redis/HTTP clients/Tracers belong in <strong>lifespan startup</strong>, and must be released in <strong>shutdown</strong> — not at module import time.</li><li><strong>Observability &amp; maintainability</strong>: Initialize logging/tracing/metrics within the lifecycle so startup/shutdown is predictable and diagnosable.</li></ul><h3>Startup (Process‑level) — Full Order</h3><pre>(1) Launch command (uvicorn / gunicorn)<br>    └─ May run multiple workers; --reload adds a reloader process<br>(2) Import Python modules (import time)<br>    └─ Avoid opening DB/Redis/HTTP connections at module top level<br>(3) Create app = FastAPI(...)<br>    ├─ Register routers / include_router / mount sub‑apps or StaticFiles<br>    ├─ Register exception handlers / declare dependencies (declarative scope)<br>    ├─ Build middleware stack (declaration order = wrapping order; first declared is outermost)<br>    └─ OpenAPI is generated lazily (first request to /openapi.json)<br>(4) ASGI lifespan.startup (including mounted sub‑apps)<br>    └─ Initialize heavy resources into app.state.*; optionally start background loops<br>(5) App is ready and starts serving requests<br>(6) On termination: lifespan.shutdown (including sub‑apps)<br>    └─ Cancel background tasks, close resources, flush logs/metrics</pre><p><strong>Key points</strong><br>- lifespan (preferred) or legacy @app.on_event(&quot;startup&quot;) is the <strong>correct place</strong> to initialize heavy resources.<br>- Sub‑apps mounted via app.mount() have <strong>their own lifecycles</strong> (startup/shutdown) in addition to the main app.</p><h3>Request (Request‑level) — Full Order</h3><pre>ASGI Server<br>  ↓<br>ASGI Middleware (outer → inner)<br>  ↓<br>Routing / sub‑app dispatch (mount)<br>  ↓<br>Dependency resolution (app → router → route; same level keeps declaration order; includes Security)<br>  ↓<br>(Optional) Custom APIRoute wrapper (get_route_handler; acts like &quot;around&quot;)<br>  ↓<br>Data parsing &amp; validation (Pydantic v2; response_model filtering/transforms)<br>  ↓<br>Endpoint function (async runs directly; def → threadpool)<br>  ↓<br>BackgroundTasks registration (executed after response is sent, within the same process)<br>  ↓<br>Dependency cleanup (finally blocks of &quot;yield&quot; dependencies)<br>  ↓<br>ASGI Middleware (inner → outer, on the way out)<br>  ↘<br>   Exception handling (nearest try/except → exception handlers → outer error middleware)</pre><blockquote><strong><em>WebSocket (brief)</em></strong><em>: ASGI Middleware → routing/handshake → </em><em>websocket_endpoint receive/send → close.<br>WebSocket routes </em><strong><em>can</em></strong><em> use dependencies, but there is </em><strong><em>no</em></strong><em> </em><em>response_model/</em><em>BackgroundTasks for WebSockets.</em></blockquote><h3>Mechanism Overview &amp; “Order Rules” — Quick Reference</h3><h3>Lifespan (startup/shutdown)</h3><ul><li><strong>Use for</strong>: creating/releasing heavy resources (DB engine, sessionmaker, Redis/MQ client, httpx client, tracing/metrics exporters, background loops).</li><li><strong>Rule</strong>: runs <strong>once per process/worker</strong>; each mounted sub‑app runs its own lifecycle too.</li></ul><h3>Pydantic BaseSettings</h3><ul><li><strong>Use for</strong>: typed configuration from environment/files.</li><li><strong>Placement</strong>: usually created before lifespan; validate/fail‑fast during startup if needed.</li></ul><h3>ASGI Middleware</h3><ul><li><strong>Use for</strong>: CORS, TrustedHost/HTTPSRedirect, GZip, access logs, tracing, rate limiting, timeouts, etc.</li><li><strong>Order</strong>: <strong>earlier declaration = more outer</strong> (first in, last out).</li></ul><h3>Dependencies (Depends(...))</h3><ul><li><strong>Levels</strong>: app → router → route; <strong>order inside a level</strong> follows the list declaration.</li><li><strong>Traits</strong>: yield for cleanup after the response; per‑request <strong>caching enabled</strong> by default (turn off with use_cache=False).</li><li><strong>Use for</strong>: Security (OAuth2, API keys), DB session provisioning, tenancy/authorization, common parameter extraction.</li></ul><h3>Custom APIRoute wrapper</h3><ul><li><strong>Position</strong>: after dependencies, before &amp; after the endpoint call; closest to an “around” interceptor.</li><li><strong>Use for</strong>: uniform error mapping, metrics tagging, timeouts, audit/SLA control.</li></ul><h3>Exception Handlers</h3><ul><li><strong>Use for</strong>: turning HTTPException, RequestValidationError, and custom exceptions into a consistent error shape.</li><li><strong>Rule</strong>: more specific types match first; anything uncaught falls back to outer error middleware.</li></ul><h3>Mounted sub‑apps / Static files</h3><ul><li><strong>Use for</strong>: app.mount(&quot;/static&quot;, StaticFiles(...)) or mounting another Starlette/FastAPI app.</li><li><strong>Rule</strong>: each sub‑app owns its routers/middleware/lifecycle.</li></ul><h3>OpenAPI / Docs</h3><ul><li><strong>Default</strong>: generated lazily; large apps may see first‑hit latency.</li><li><strong>Tip</strong>: pre‑build with app.openapi() during startup and cache it.</li></ul><h3>Constraints &amp; Common Pitfalls</h3><ol><li><strong>Multi‑workers/replicas re‑enter startup</strong></li></ol><ul><li>Migrations, cache warming, or scheduled jobs <strong>may run multiple times</strong>.</li><li><strong>Mitigation</strong>: design for idempotency; use distributed locks (Postgres advisory lock, Redis lock) or leader election.</li></ul><p><strong>2. Dev mode </strong><strong>--reload uses two processes</strong></p><ul><li>The reloader and the child process both run startup.</li><li><strong>Mitigation</strong>: never open connections at import time; initialize in lifespan only.</li></ul><p><strong>3. Gunicorn </strong><strong>preload_app=True</strong></p><ul><li>Opening connections during import causes bad inheritance into workers.</li><li><strong>Mitigation</strong>: keep heavy initialization exclusively in lifespan.</li></ul><p><strong>4. No global upload size limit</strong></p><ul><li>Large uploads/streams can exhaust memory.</li><li><strong>Mitigation</strong>: limit body size at your reverse proxy (Nginx/Envoy); use StreamingResponse; avoid loading whole files in memory.</li></ul><p>5. <strong>ield dependency cleanup timing</strong></p><ul><li>Cleanup runs <strong>after</strong> the response is sent.</li><li><strong>Mitigation</strong>: do not place long jobs there; move them to BackgroundTasks or external job queues.</li></ul><p><strong>6. Timeouts/rate limits not built‑in</strong></p><ul><li><strong>Mitigation</strong>: implement via middleware/APIRoute, or enforce at API gateway/reverse proxy (Nginx/Kong/Envoy).</li></ul><p><strong>7. Resources not closed (FD/memory leaks)</strong></p><ul><li>httpx.AsyncClient, DB engines, background loops not closed.</li><li><strong>Mitigation</strong>: close/dispose/cancel during shutdown; use gather(return_exceptions=True).</li></ul><p><strong>8. Proxy/CORS/Host trust misconfiguration</strong></p><ul><li>Wrong client IP/scheme, overly permissive CORS.</li><li><strong>Mitigation</strong>: ProxyHeadersMiddleware (or --proxy-headers), TrustedHostMiddleware, strict CORS allow‑lists.</li></ul><p><strong>9. Slow OpenAPI generation for large apps</strong></p><ul><li><strong>Mitigation</strong>: pre‑generate/cache OpenAPI during startup; or split the app.</li></ul><h3>Practical Startup Checklist (paste into your PR)</h3><p><strong>Config &amp; dependencies</strong> — [ ] BaseSettings loads env; validate required fields; fail‑fast on invalid config<br>- [ ] Store config/handles in app.state.* (or a typed AppState helper)</p><p><strong>Resources</strong> — [ ] In lifespan: create AsyncEngine, async_sessionmaker, Redis/MQ client, httpx.AsyncClient<br>- [ ] In shutdown: close/dispose/cancel in order; gather(..., return_exceptions=True)</p><p><strong>Observability</strong> — [ ] Structured logging (JSON)<br>- [ ] Tracing (OpenTelemetry) + exporter<br>- [ ] Metrics (Prometheus): request histograms, error rates, dependency health</p><p><strong>Request pipeline</strong> — [ ] Middleware: CORS, TrustedHost/HTTPSRedirect, ProxyHeaders, GZip, access‑log/trace, (custom) timeout/rate‑limit<br>- [ ] Dependencies: Security, DB session, tenancy/authorization, common params<br>- [ ] APIRoute wrapper: uniform errors, metrics tags, per‑route timeouts</p><p><strong>Error handling</strong> — [ ] Map HTTPException, RequestValidationError, and business exceptions to a consistent error shape</p><p><strong>Health checks</strong> — [ ] /live: no external deps, just “I’m alive”<br>- [ ] /ready: lightweight pings to critical deps (DB/Redis/MQ)</p><p><strong>OpenAPI/Docs</strong> — [ ] Pre‑build/cached app.openapi() if needed<br>- [ ] Hide internal endpoints with include_in_schema=False</p><h3>Production Template (lifespan + middleware + dependencies + exception handling + health checks)</h3><pre># app.py<br>from contextlib import asynccontextmanager<br>import asyncio<br>from typing import Optional, List<br>import httpx<br>from fastapi import FastAPI, Request, Depends, HTTPException<br>from fastapi.responses import JSONResponse<br>from fastapi.routing import APIRoute, APIRouter<br>from pydantic import BaseSettings<br>from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker, AsyncEngine<br>from sqlalchemy import text<br>from starlette.middleware.base import BaseHTTPMiddleware<br>from starlette.middleware.cors import CORSMiddleware<br>from starlette.middleware.trustedhost import TrustedHostMiddleware<br># ---------------------------<br># Settings<br># ---------------------------<br>class Settings(BaseSettings):<br>    db_dsn: str = &quot;postgresql+asyncpg://user:pass@localhost/db&quot;<br>    redis_url: str = &quot;redis://localhost:6379/0&quot;  # placeholder<br>    http_timeout: float = 5.0<br>    allowed_hosts: List[str] = [&quot;example.com&quot;, &quot;localhost&quot;, &quot;127.0.0.1&quot;]<br>settings = Settings()<br># ---------------------------<br># App State (typed)<br># ---------------------------<br>class AppState:<br>    engine: Optional[AsyncEngine] = None<br>    Session: Optional[async_sessionmaker] = None<br>    http: Optional[httpx.AsyncClient] = None<br>    bg_tasks: list[asyncio.Task] = []<br># ---------------------------<br># Lifespan<br># ---------------------------<br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    # --- startup ---<br>    # DB<br>    engine = create_async_engine(settings.db_dsn, pool_pre_ping=True)<br>    Session = async_sessionmaker(engine, expire_on_commit=False)<br>    # HTTP client<br>    http = httpx.AsyncClient(timeout=settings.http_timeout)<br>    # Lightweight readiness probe (fail-fast)<br>    async with engine.connect() as conn:<br>        await conn.execute(text(&quot;SELECT 1&quot;))<br>    # Background loop example<br>    async def ticker():<br>        try:<br>            while True:<br>                await asyncio.sleep(60)<br>        except asyncio.CancelledError:<br>            pass  # graceful stop<br>    t = asyncio.create_task(ticker())<br>    # Attach to state<br>    app.state.engine = engine<br>    app.state.Session = Session<br>    app.state.http = http<br>    app.state.bg_tasks = [t]<br>    # Optionally pre-build OpenAPI cache to avoid first-hit latency<br>    app.openapi()<br>    yield<br>    # --- shutdown ---<br>    for task in app.state.bg_tasks:<br>        task.cancel()<br>    await asyncio.gather(*app.state.bg_tasks, return_exceptions=True)<br>    await http.aclose()<br>    await engine.dispose()<br># ---------------------------<br># FastAPI app<br># ---------------------------<br>app = FastAPI(lifespan=lifespan)<br># ---------------------------<br># Middleware (outer → inner)<br># ---------------------------<br># Host safety<br>app.add_middleware(TrustedHostMiddleware, allowed_hosts=settings.allowed_hosts)<br># CORS<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;https://example.com&quot;, &quot;http://localhost:3000&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br>class AccessLogMiddleware(BaseHTTPMiddleware):<br>    async def dispatch(self, request: Request, call_next):<br>        # before<br>        response = await call_next(request)<br>        # after (you can push metrics/trace here)<br>        return response<br>app.add_middleware(AccessLogMiddleware)<br># ---------------------------<br># Dependencies<br># ---------------------------<br>async def get_session(request: Request):<br>    &quot;&quot;&quot;Provide a DB session per request (cached).&quot;&quot;&quot;<br>    Session = request.app.state.Session<br>    async with Session() as session:<br>        yield session  # cleanup after response sent<br>async def require_tenant(request: Request):<br>    &quot;&quot;&quot;Simple multi-tenant guard.&quot;&quot;&quot;<br>    tenant = request.headers.get(&quot;x-tenant&quot;)<br>    if not tenant:<br>        raise HTTPException(status_code=400, detail=&quot;Missing tenant&quot;)<br>    return tenant<br># ---------------------------<br># Exception Handlers (uniform error shape)<br># ---------------------------<br>@app.exception_handler(HTTPException)<br>async def http_exc_handler(_: Request, exc: HTTPException):<br>    return JSONResponse({&quot;ok&quot;: False, &quot;error&quot;: exc.detail}, status_code=exc.status_code)<br># Optional: add handler for RequestValidationError and others if desired.<br># ---------------------------<br># APIRoute wrapper (around)<br># ---------------------------<br>class WrappedRoute(APIRoute):<br>    def get_route_handler(self):<br>        original = super().get_route_handler()<br>        async def wrapped(request: Request):<br>            try:<br>                # pre: inject trace/metrics tags if needed<br>                resp = await original(request)<br>                # post: record success metrics<br>                return resp<br>            except Exception:<br>                # post: record failure metrics, then re-raise<br>                raise<br>        return wrapped<br>router = APIRouter(<br>    prefix=&quot;/api&quot;,<br>    route_class=WrappedRoute,<br>    dependencies=[Depends(require_tenant)]  # app/router/route layered dependencies<br>)<br>@router.get(&quot;/items&quot;)<br>async def list_items(tenant: str = Depends(require_tenant), session=Depends(get_session)):<br>    # business logic...<br>    return {&quot;ok&quot;: True, &quot;tenant&quot;: tenant}<br>app.include_router(router)<br># ---------------------------<br># Health endpoints<br># ---------------------------<br>@app.get(&quot;/live&quot;, include_in_schema=False)<br>async def liveness():<br>    # don&#39;t touch external deps here<br>    return {&quot;ok&quot;: True}<br>@app.get(&quot;/ready&quot;, include_in_schema=False)<br>async def readiness(request: Request):<br>    # light-weight checks for deps<br>    try:<br>        async with request.app.state.engine.connect() as conn:<br>            await conn.execute(text(&quot;SELECT 1&quot;))<br>        # you can ping Redis/MQ here if needed<br>        return {&quot;ok&quot;: True}<br>    except Exception:<br>        return JSONResponse({&quot;ok&quot;: False}, status_code=503)</pre><h3>Testing &amp; Local Development Notes</h3><ul><li><strong>--reload runs startup twice</strong>: move non‑idempotent steps into lifespan and make them idempotent.</li><li><strong>TestClient(app, lifespan=&quot;on&quot;)</strong>: run startup/shutdown within tests for realistic scenarios.</li><li><strong>Blocking work</strong>: wrap small blocking I/O/CPU with run_in_threadpool to avoid event‑loop stalls.</li><li><strong>Multiple workers</strong>: with uvicorn --workers N or gunicorn, each worker runs lifespan; plan migrations/scheduling/warmups accordingly.</li></ul><h3>One‑Sentence Summary</h3><blockquote><strong><em>Initialize all heavy/observable resources in </em></strong><strong><em>lifespan, structure the request chain via middleware + dependencies + APIRoute, split liveness/readiness, ensure idempotent startup, and close resources cleanly.</em></strong><em><br>Done right, your FastAPI app behaves predictably across local dev, single‑process runs, gunicorn multi‑process, and Kubernetes multi‑replica deployments.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53e29dcb9249" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/fastapi-starlette-lifecycle-guide-startup-order-pitfalls-best-practices-and-a-production-ready-53e29dcb9249">FastAPI/Starlette Lifecycle Guide: Startup Order, Pitfalls, Best Practices, and a Production‑Ready…</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Jobs & Workers — A Complete, Practical Guide]]></title>
            <link>https://medium.com/codecodecode/python-jobs-workers-a-complete-practical-guide-cf842cfe33d7?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf842cfe33d7</guid>
            <category><![CDATA[jobs]]></category>
            <category><![CDATA[workers]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 17:20:07 GMT</pubDate>
            <atom:updated>2025-10-12T17:20:07.225Z</atom:updated>
            <content:encoded><![CDATA[<h3>Python Jobs &amp; Workers — A Complete, Practical Guide</h3><p><em>Cron, Schedulers, Queues, Workflows, CPU-/I/O-Bound</em></p><blockquote><em>A systemized, end-to-end playbook to help you pick the right approach — from a single cron entry to cloud-scale distributed workers. Code examples use English comments to align with docs and global teams.</em></blockquote><h3>TL;DR (Fast Answers)</h3><ul><li><strong>Lightweight &amp; simple schedules</strong> → System cron/systemd timers or in-app <strong>APScheduler</strong>.</li><li><strong>Asynchronous background tasks</strong> → A task queue such as <strong>Celery</strong>, <strong>Dramatiq</strong>, <strong>RQ</strong>, or <strong>Huey</strong> backed by <strong>RabbitMQ/Redis/SQS</strong>.</li><li><strong>Complex pipelines &amp; backfills</strong> → Workflow orchestrators like <strong>Apache Airflow</strong> or <strong>Prefect</strong> with DAGs.</li><li><strong>I/O-bound concurrency</strong> → asyncio (non-blocking clients), or Celery with gevent/eventlet.</li><li><strong>CPU-bound workloads</strong> → Multiprocessing (Celery prefork, ProcessPoolExecutor) or distributed compute (<strong>Ray</strong>, <strong>Dask</strong>).</li><li><strong>Cloud-native</strong> → Kubernetes CronJob for schedules; Deployment + HPA for workers; add DLQ, idempotency, retries, backoff, and observability.</li></ul><h3>Why this guide? (Mental model)</h3><p>Building “jobs &amp; workers” isn’t about picking a brand name framework. It’s about aligning four things:</p><ol><li><strong>Triggering</strong> — When do jobs start? (cron, events, API, human)</li><li><strong>Workload shape</strong> — I/O-bound vs CPU-bound, message size, latency/SLA.</li><li><strong>Reliability semantics</strong> — At-least-once + idempotency vs exactly-once (rare; usually emulated).</li><li><strong>Operate at scale</strong> — Containers? autoscale? backpressure? DLQ? tracing &amp; metrics?</li></ol><p>Keep that model in mind while reading the options below.</p><h3>Key concepts (Glossary)</h3><ul><li><strong>Job/Task</strong>: Independent unit of work — function + inputs + policy (retries, timeout).</li><li><strong>Worker</strong>: Long-running process that pulls &amp; executes tasks from a queue.</li><li><strong>Broker/Queue</strong>: Persists &amp; dispatches tasks (RabbitMQ, Redis, SQS, etc.).</li><li><strong>Scheduler</strong>: Decides <em>when</em> to trigger tasks (cron, APScheduler, Celery Beat, Airflow Scheduler, Kubernetes CronJob).</li><li><strong>Result backend</strong>: Stores task states/results (Redis, DB, object storage).</li><li><strong>DLQ (Dead Letter Queue)</strong>: Holding area for repeatedly failing jobs.</li><li><strong>Idempotency</strong>: Re-running with the same key does not change outcome.</li><li><strong>Backpressure</strong>: Slow downstream → throttle producers/workers to prevent overload.</li></ul><h3>Common scenarios &amp; choices</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WV0ROSemsvRHslymDcMxQQ.png" /></figure><h3>Option landscape</h3><h3>1) Lightweight scheduling</h3><p><strong>Use when:</strong> one server or a handful of containers; low complexity.</p><ul><li><strong>System cron / systemd timers</strong> — Stable, zero extra infra, but limited central control/visibility.</li><li><strong>APScheduler</strong> — In-app scheduler; supports cron/interval/date triggers and job stores (e.g., SQL).</li></ul><h4>APScheduler example (embed in your app)</h4><pre>from apscheduler.schedulers.background import BackgroundScheduler<br>from apscheduler.triggers.cron import CronTrigger<br><br>def cleanup():<br>    # domain logic here<br>    print(&quot;cleanup!&quot;)<br>if __name__ == &quot;__main__&quot;:<br>    scheduler = BackgroundScheduler()<br>    scheduler.add_job(cleanup, CronTrigger(hour=2, minute=30))  # 02:30 daily<br>    scheduler.start()<br>    # keep app alive (web server, or a sleep loop)</pre><h3>2) Task queues (the workhorse)</h3><p><strong>Use when:</strong> asynchronous background jobs, retries, backpressure, multi-worker scaling.</p><ul><li><strong>Celery</strong> — Mature &amp; feature-rich; multiple concurrency models (prefork, gevent, eventlet, threads); routing, chaining, chords.</li><li><strong>Dramatiq</strong> — Clean API, fast, RabbitMQ/Redis support.</li><li><strong>RQ</strong> — Minimalistic Redis-based; great for small teams.</li><li><strong>Huey</strong> — Small, pragmatic; Redis or SQLite.</li></ul><h4>Celery minimal skeleton</h4><pre># celery_app.py<br>from celery import Celery<br><br>app = Celery(<br>    &quot;demo&quot;,<br>    broker=&quot;amqp://user:pass@rabbitmq:5672//&quot;,  # or redis://<br>    backend=&quot;redis://redis:6379/0&quot;,<br>)<br>@app.task(bind=True, autoretry_for=(Exception,), retry_backoff=True, retry_kwargs={&quot;max_retries&quot;: 5})<br>def fetch_url(self, url: str) -&gt; str:<br>    &quot;&quot;&quot;I/O-bound example with retry + exponential backoff.&quot;&quot;&quot;<br>    import requests<br>    r = requests.get(url, timeout=10)<br>    r.raise_for_status()<br>    return r.text[:200]</pre><h4>Run workers</h4><pre># I/O-bound → many lightweight greenlets<br>celery -A celery_app.app worker -l info -P gevent -c 200</pre><pre># CPU-bound → true parallelism via multiple processes<br>celery -A celery_app.app worker -l info -P prefork -c 4</pre><blockquote><strong><em>Celery best practices</em></strong><em><br>- Prefer </em><strong><em>RabbitMQ</em></strong><em> for large/complex topologies; </em><strong><em>Redis</em></strong><em> is fine for small/medium.<br>- Use </em><em>acks_late=True (ack after completion) + tune </em><em>worker_prefetch_multiplier to balance fairness vs throughput.<br>- Implement </em><strong><em>idempotency keys</em></strong><em> at the business layer (DB unique keys, de-dup tables, optimistic locks).<br>- Define </em><strong><em>timeouts</em></strong><em>, </em><strong><em>max retries</em></strong><em>, and </em><strong><em>exponential backoff</em></strong><em> per task.<br>- Observe using Flower/metrics; add OpenTelemetry traces from API → queue → worker → downstreams.</em></blockquote><h4>Dramatiq one-file sample</h4><pre># tasks.py<br>import dramatiq<br>from dramatiq.brokers.rabbitmq import RabbitmqBroker<br><br>broker = RabbitmqBroker(url=&quot;amqp://user:pass@rabbitmq:5672//&quot;)<br>dramatiq.set_broker(broker)<br>@dramatiq.actor(max_retries=5, min_backoff=1000)<br>def process_image(image_id: str):<br>    # For CPU-bound, consider offloading to subprocess/pool.<br>    ...</pre><h3>3) Workflow orchestrators (DAGs)</h3><p><strong>Use when:</strong> dependencies, backfills, SLAs, complex dataflows.</p><ul><li><strong>Apache Airflow</strong> — Enterprise standard; rich ecosystem, sensors, operators.</li><li><strong>Prefect</strong> — Pythonic developer experience, local/cloud execution models.</li></ul><p>These orchestrate <em>when</em> and <em>how</em> to run tasks across systems; they can trigger queue jobs or run code directly.</p><h3>4) Distributed compute</h3><p><strong>Use when:</strong> the work <em>is</em> the compute (heavy CPU/GPU), not just task dispatch.</p><ul><li><strong>Ray / Dask</strong> — Distribute Python functions/datasets across cores and nodes; integrate with ML stacks.</li><li><strong>multiprocessing / ProcessPoolExecutor</strong> — Single-node parallelism; a great first step for CPU-bound tasks.</li></ul><h4>CPU-bound quick start with ProcessPoolExecutor</h4><pre>from concurrent.futures import ProcessPoolExecutor, as_completed<br><br>def heavy(n: int) -&gt; int:<br>    # CPU-heavy loop (toy example)<br>    s = 0<br>    for i in range(10_000_000):<br>        s += (i * n) % 97<br>    return s<br>if __name__ == &quot;__main__&quot;:<br>    with ProcessPoolExecutor(max_workers=4) as pool:<br>        futures = [pool.submit(heavy, i) for i in range(8)]<br>        for f in as_completed(futures):<br>            print(f.result())</pre><h3>5) Cloud-native &amp; serverless</h3><ul><li><strong>Kubernetes</strong> — CronJob for schedules; Deployment for workers; HPA for autoscaling; add DLQ, PDBs, liveness/readiness, resource limits.</li><li><strong>Serverless</strong> — (e.g., Lambda + EventBridge + SQS + Step Functions): minimal ops, pay-per-use; mind cold starts, timeouts, idempotency.</li></ul><h4>Kubernetes CronJob example</h4><pre>apiVersion: batch/v1<br>kind: CronJob<br>metadata:<br>  name: report-job<br>spec:<br>  schedule: &quot;30 2 * * *&quot;  # 02:30 daily<br>  jobTemplate:<br>    spec:<br>      template:<br>        spec:<br>          containers:<br>            - name: report<br>              image: ghcr.io/acme/report:1.2.3<br>              args: [&quot;python&quot;, &quot;generate_report.py&quot;]<br>          restartPolicy: OnFailure</pre><h3>Choosing wisely (Decision tree)</h3><ol><li><strong>Only a handful of simple schedules?</strong> → cron / APScheduler / K8s CronJob.</li><li><strong>Need async execution, retries, backpressure, multi-workers?</strong> → Task queue.</li><li><strong>Tasks have dependencies/backfills/SLA?</strong> → Workflow orchestrator.</li><li><strong>Bottleneck = I/O latency?</strong> → asyncio or green-worker models.</li><li><strong>Bottleneck = CPU/GPU?</strong> → Multiprocessing or Ray/Dask, not threads.</li><li><strong>Centralized ops &amp; autoscaling?</strong> → Containers + K8s + metrics-based HPA.</li></ol><h3>I/O-bound vs CPU-bound</h3><h3>I/O-bound (waiting on network/disk/DB)</h3><ul><li>Prefer <strong>non-blocking I/O</strong> (aiohttp, httpx[async], asyncpg, etc.).</li><li>With queues, pick <strong>gevent/eventlet</strong> workers or run pure asyncio + external broker.</li><li>Tune high concurrency; hard <strong>timeouts</strong> and <strong>backoff</strong> prevent dog-piles.</li></ul><h3>CPU-bound (pure computation)</h3><ul><li>Use <strong>multiprocessing</strong> to bypass the GIL (<strong>prefork</strong> in Celery).</li><li>Consider <strong>Ray/Dask</strong> for multi-node scaling and data-parallel workloads.</li><li>If libraries release the GIL (e.g., NumPy, some codecs), threads can help — profile to verify.</li></ul><h3>Production blueprint (Docker Compose)</h3><pre>version: &quot;3.9&quot;<br>services:<br>  rabbitmq:<br>    image: rabbitmq:3-management<br>    ports: [&quot;5672:5672&quot;, &quot;15672:15672&quot;]<br><br>redis:<br>    image: redis:7<br>  app:<br>    build: .<br>    env_file: .env<br>    environment:<br>      - CELERY_BROKER_URL=amqp://guest@rabbitmq//<br>      - CELERY_RESULT_BACKEND=redis://redis:6379/0<br>    depends_on: [rabbitmq, redis]<br>  worker:<br>    build: .<br>    command: celery -A celery_app.app worker -l info -P prefork -c 4<br>    env_file: .env<br>    depends_on: [rabbitmq, redis]<br>  beat:<br>    build: .<br>    command: celery -A celery_app.app beat -l info<br>    env_file: .env<br>    depends_on: [rabbitmq, redis]<br>  flower:<br>    image: mher/flower<br>    environment:<br>      - FLOWER_BROKER=amqp://guest@rabbitmq//<br>    ports: [&quot;5555:5555&quot;]<br>    depends_on: [rabbitmq]</pre><blockquote><strong><em>Notes</em></strong><em> — For I/O-bound workloads, run a separate </em><strong><em>gevent/eventlet</em></strong><em> worker pool (high </em><em>-c), and keep CPU tasks on </em><strong><em>prefork</em></strong><em>workers.<br>- Split queues by workload (</em><em>io, </em><em>cpu) and route tasks accordingly.</em></blockquote><h3>asyncio worker (minimal deps)</h3><p>Suitable for medium traffic and push-based API ingestion. Add a real broker (Redis Streams, NATS, Kafka) when scaling across nodes.</p><pre># app.py (FastAPI + asyncio.Queue)<br>import asyncio<br>from fastapi import FastAPI<br><br>app = FastAPI()<br>queue: asyncio.Queue[str] = asyncio.Queue()<br>@app.post(&quot;/tasks&quot;)<br>async def enqueue(url: str):<br>    await queue.put(url)<br>    return {&quot;queued&quot;: url}<br>async def worker():<br>    while True:<br>        url = await queue.get()<br>        try:<br>            import aiohttp<br>            async with aiohttp.ClientSession() as s:<br>                async with s.get(url, timeout=10) as r:<br>                    body = await r.text()<br>                    print(body[:80])<br>        except Exception as e:<br>            # TODO: retries/backoff/DLQ<br>            print(&quot;err&quot;, e)<br>        finally:<br>            queue.task_done()<br><br>@app.on_event(&quot;startup&quot;)<br>async def startup():<br>    for _ in range(200):  # concurrency<br>        asyncio.create_task(worker())</pre><h3>Reliability checklist</h3><ul><li><strong>Retries &amp; backoff</strong> — Always bounded; add jitter to reduce herds.</li><li><strong>Timeouts</strong> — Hard limits for tasks and I/O calls.</li><li><strong>Idempotency</strong> — Business keys, dedup tables, optimistic locking, upserts.</li><li><strong>DLQ</strong> — Inspect, alert, and reprocess with care; store context for triage.</li><li><strong>Rate limiting / quotas</strong> — Per tenant/customer/source to protect downstreams.</li><li><strong>Batching &amp; sharding</strong> — Break big jobs; avoid giant payloads.</li><li><strong>Circuit breakers &amp; bulkheads</strong> — Isolate failures, shed load early.</li><li><strong>Backpressure &amp; flow control</strong> — Measure queue depth &amp; latency; slow producers when needed.</li></ul><h3>Observability essentials</h3><ul><li><strong>Metrics</strong> — queue depth, enqueue/dequeue rates, success/failure, retries, task latency percentiles.</li><li><strong>Structured logs</strong> — correlation IDs (request_id, trace_id) across producers/workers.</li><li><strong>Tracing</strong> — end-to-end spans (API → Broker → Worker → Downstream). OpenTelemetry SDKs are helpful.</li><li><strong>Dashboards &amp; alerts</strong> — SLOs on end-to-end latency &amp; error budgets, not just CPU graphs.</li></ul><h3>Security &amp; data handling</h3><ul><li><strong>Secrets</strong> — Use a secret manager (not .env in repos). Rotate regularly.</li><li><strong>RBAC</strong> — Separate credentials for producers/workers; least privilege for queues.</li><li><strong>PII</strong> — Avoid raw PII in payloads; tokenize or reference via IDs.</li><li><strong>Validation</strong> — Strict input schema; version payloads (envelope {version, type, data}).</li><li><strong>Tenancy</strong> — Per-tenant queues or routing keys to isolate noisy neighbors.</li></ul><h3>Testing strategy</h3><ul><li><strong>Unit tests</strong> — Pure function logic of tasks.</li><li><strong>Integration tests</strong> — Ephemeral broker (dockerized) with real worker for retries/acks.</li><li><strong>Idempotency tests</strong> — Re-submit the same task with the same key; assert no double-effects.</li><li><strong>Property-based tests</strong> — Payload fuzzing; ensure invariants hold.</li><li><strong>Load tests</strong> — Queue depth behavior, backpressure, and tail latency under burst traffic.</li></ul><h3>Migration path</h3><ol><li>Start with <strong>cron/APScheduler</strong> for a few jobs.</li><li>Introduce a <strong>task queue</strong> when async + retries/backpressure are needed.</li><li>Split <strong>I/O vs CPU</strong> workloads and route to separate worker pools &amp; queue names.</li><li>Add <strong>observability + DLQ</strong>; define SLOs.</li><li>Move to <strong>Kubernetes</strong> for centralized ops and autoscaling.</li><li>Introduce <strong>workflow orchestration</strong> (Airflow/Prefect) for DAGs and backfills.</li><li>For heavy compute, adopt <strong>Ray/Dask</strong> or specialized GPU pipelines.</li></ol><h3>Quick reference tables</h3><h3>Frameworks &amp; where they shine</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EYuavoHPKWc9RUuh3gncXA.png" /></figure><h3>I/O vs CPU quick picks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3F4cvzKFYlLdiRFHI2wiA.png" /></figure><h3>Workload-based queue split</h3><ul><li>Queue <strong>io</strong> (gevent workers): HTTP calls, DB syncs, file I/O.</li><li>Queue <strong>cpu</strong> (prefork workers): image transforms, compression, heavy parsing.</li><li>Route tasks explicitly (e.g., queue=&#39;io&#39; vs queue=&#39;cpu&#39;) and scale pools independently.</li></ul><h3>Pitfalls to avoid</h3><ul><li>Mixing I/O-heavy and CPU-heavy tasks in the same worker pool → under-utilization or starvation.</li><li>Unbounded concurrency without timeouts/backoff → amplifies outages.</li><li>Exactly-once fantasies → embrace at-least-once with <strong>idempotency</strong> and dedup.</li><li>Over-reliance on result backends → consider emitting outcomes to a durable store/event log instead.</li><li>Ignoring payload versioning → schema drift will bite future you.</li></ul><h3>Minimal templates</h3><pre># Celery task with idempotency key<br>@app.task(bind=True, autoretry_for=(Exception,), retry_backoff=True, retry_kwargs={&quot;max_retries&quot;: 5})<br>def settle_payment(self, order_id: str, amount_cents: int, idem_key: str):<br>    &quot;&quot;&quot;Idempotent effect via unique constraint on (idem_key).&quot;&quot;&quot;<br>    with db.transaction():<br>        if db.idem_exists(idem_key):<br>            return &quot;duplicate&quot;<br>        db.insert_settlement(order_id, amount_cents, idem_key)  # unique constraint on idem_key<br>        # call PSP, etc.<br>        return &quot;ok&quot;<br><br># Celery routing by queue<br># send I/O task<br>fetch_url.apply_async(args=[&quot;https://example.com&quot;], queue=&quot;io&quot;)<br># send CPU task<br>heavy_math.apply_async(args=[42], queue=&quot;cpu&quot;)</pre><blockquote><strong><em>Kubernetes HPA target idea (pseudo):</em></strong><em> expose queue depth as a custom metric, scale workers when depth &gt; threshold.</em></blockquote><h3>Wrap-up</h3><p>Pick the <strong>lightest tool</strong> that gets the job done today, but design for <strong>idempotency, retries, DLQ, and observability</strong> from day one. Separate <strong>I/O</strong> from <strong>CPU</strong> workloads and scale them independently. When complexity grows — add a queue, then orchestration, then distributed compute — without throwing away earlier pieces.</p><h3>Appendix A — Architecture sketch</h3><pre>[API/Gateway] --&gt; [Broker/Queue] --&gt; [Workers x N] --&gt; [DB/Cache/FS]<br>       |               |                   |<br>   (Scheduler)     (DLQ/Retry)        (Result backend)</pre><h3>Appendix B — Payload envelope</h3><pre>{<br>  &quot;version&quot;: 2,<br>  &quot;type&quot;: &quot;user.report.generate&quot;,<br>  &quot;idempotency_key&quot;: &quot;ur-2025-10-13-42&quot;,<br>  &quot;data&quot;: {<br>    &quot;user_id&quot;: &quot;u_123&quot;,<br>    &quot;period&quot;: &quot;2025-09&quot;<br>  },<br>  &quot;trace&quot;: {<br>    &quot;request_id&quot;: &quot;req_abc&quot;,<br>    &quot;parent_span&quot;: &quot;span_xyz&quot;<br>  }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf842cfe33d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/python-jobs-workers-a-complete-practical-guide-cf842cfe33d7">Python Jobs &amp; Workers — A Complete, Practical Guide</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Practical Guide to Python Caching: from __pycache__ to LRU/TTL/Single-Flight, Redis, and HTTP]]></title>
            <link>https://medium.com/codecodecode/the-practical-guide-to-python-caching-from-pycache-to-lru-ttl-single-flight-redis-and-http-28b51d4063ac?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b51d4063ac</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[lru-cache]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 17:27:46 GMT</pubDate>
            <atom:updated>2025-10-08T17:27:46.722Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>TL;DR</em></strong><em><br>- </em><strong><em>Config/constants</em></strong><em>: wrap </em><em>get_settings() with </em><em>@lru_cache(maxsize=1) for a zero-cost speedup.<br>- </em><strong><em>Expensive lookups</em></strong><em>: use </em><strong><em>Single-Flight + TTL</em></strong><em> to coalesce concurrent requests and flatten spikes; add </em><strong><em>Redis</em></strong><em> for multi-process / multi-pod sharing.<br>- </em><strong><em>HTTP layer</em></strong><em>: serve with </em><strong><em>ETag / Cache-Control</em></strong><em>; client-side (or scripts) can use </em><em>requests-cache.<br>- </em><strong><em>Containers</em></strong><em>: </em><em>PYTHONDONTWRITEBYTECODE=1 or set </em><em>PYTHONPYCACHEPREFIX=/var/cache/pycache.<br>- </em><strong><em>Tests &amp; observability</em></strong><em>: clear caches in pytest; export hit ratio and latency to Prometheus; always invalidate on writes.</em></blockquote><h3>Why caching matters</h3><p>Caching is not only about being <strong>fast</strong>; it is also about being <strong>stable</strong>. A good cache absorbs spikes so your DB or 3rd-party API does not melt down under bursty traffic. But caching is a double-edged sword: consistency, <strong>cache stampedes</strong>, and memory bloat are common traps. This guide walks from <strong>practical first steps</strong> to <strong>production-ready patterns</strong>, with drop-in snippets you can paste into your codebase.</p><h3>Mental model: four layers of caching</h3><ol><li><strong>Bytecode cache</strong> (__pycache__/*.pyc): speeds up imports; unrelated to your business logic.</li><li><strong>Import cache</strong> (sys.modules): a module is loaded once per process.</li><li><strong>In-process program cache</strong>: lru_cache / cache / cached_property / in-memory TTL dicts.</li><li><strong>Shared cache</strong> across workers/pods: Redis/Memcached with invalidation; HTTP/CDN for content.</li></ol><h3>Hands-on 1: Cache your settings object (FastAPI/Pydantic)</h3><p>Avoid rebuilding settings or re-reading .env on every dependency resolution. This is the easiest, safest win.</p><pre># app/core/settings.py<br>from functools import lru_cache<br>from pydantic_settings import BaseSettings, SettingsConfigDict<br><br>class Settings(BaseSettings):<br>    &quot;&quot;&quot;App settings loaded from environment or .env.&quot;&quot;&quot;<br>    app_name: str = &quot;remote-lock-cloud&quot;<br>    database_url: str<br>    model_config = SettingsConfigDict(<br>        env_file=&quot;.env&quot;,<br>        env_file_encoding=&quot;utf-8&quot;,<br>        extra=&quot;ignore&quot;,<br>    )<br>@lru_cache(maxsize=1)<br>def get_settings() -&gt; Settings:<br>    &quot;&quot;&quot;Construct once per process; fast and thread-safe for reads.&quot;&quot;&quot;<br>    return Settings()</pre><pre># app/main.py<br>from fastapi import FastAPI, Depends<br>from app.core.settings import get_settings<br><br>app = FastAPI()<br>@app.get(&quot;/ping&quot;)<br>def ping(settings=Depends(get_settings)):<br>    # Reuse the cached Settings instance<br>    return {&quot;app&quot;: settings.app_name}</pre><p><strong>Hot-reload option</strong>: clear the cache on SIGHUP and the next access rebuilds it.</p><pre># app/core/reload.py<br>import signal<br>from app.core.settings import get_settings<br><br>def _reload_settings(*_):<br>    &quot;&quot;&quot;Clear cached settings on SIGHUP.&quot;&quot;&quot;<br>    get_settings.cache_clear()<br>signal.signal(signal.SIGHUP, _reload_settings)</pre><h3>Hands-on 2: Single-Flight + TTL (async) to prevent stampedes</h3><p><strong>Scenario</strong>: many concurrent requests for the <strong>same key</strong> (DB or external API). You want <strong>one fetch per key</strong>, others await the same result, and the result lives for a <strong>TTL</strong>.</p><pre># app/utils/async_singleflight_ttl.py<br>import asyncio, time<br>from typing import Any, Callable, Awaitable, Dict, Tuple<br><br>class AsyncSingleFlightTTL:<br>    &quot;&quot;&quot;Per-key single-flight with TTL in-memory cache (process-local).&quot;&quot;&quot;<br>    def __init__(self, ttl_seconds: float = 10.0) -&gt; None:<br>        self.ttl = ttl_seconds<br>        self._locks: Dict[Any, asyncio.Lock] = {}<br>        self._cache: Dict[Any, Tuple[float, Any]] = {}<br>    async def get(self, key: Any, fetcher: Callable[[], Awaitable[Any]]) -&gt; Any:<br>        &quot;&quot;&quot;Return cached value if fresh; otherwise single-flight fetch.&quot;&quot;&quot;<br>        now = time.monotonic()<br>        exp_val = self._cache.get(key)<br>        if exp_val and exp_val[0] &gt; now:<br>            return exp_val[1]<br>        lock = self._locks.setdefault(key, asyncio.Lock())<br>        async with lock:<br>            exp_val = self._cache.get(key)<br>            if exp_val and exp_val[0] &gt; time.monotonic():<br>                return exp_val[1]<br>            val = await fetcher()<br>            self._cache[key] = (time.monotonic() + self.ttl, val)<br>            return val<br>    async def invalidate(self, key: Any | None = None) -&gt; None:<br>        &quot;&quot;&quot;Invalidate one key or the entire cache.&quot;&quot;&quot;<br>        if key is None:<br>            self._cache.clear()<br>        else:<br>            self._cache.pop(key, None)</pre><p>Apply it to an external API or a DB query:</p><pre># app/services/users.py<br>import httpx<br>from app.utils.async_singleflight_ttl import AsyncSingleFlightTTL<br><br>_user_sf = AsyncSingleFlightTTL(ttl_seconds=30)<br>async def get_user_profile(user_id: str) -&gt; dict:<br>    &quot;&quot;&quot;Fetch user profile with per-key single-flight and TTL.&quot;&quot;&quot;<br>    async def fetch():<br>        async with httpx.AsyncClient(timeout=5) as client:<br>            r = await client.get(f&quot;https://api.example.com/users/{user_id}&quot;)<br>            r.raise_for_status()<br>            return r.json()<br>    return await _user_sf.get(user_id, fetch)</pre><p>Invalidate on writes (avoid stale reads after updates):</p><pre># after a successful PUT /users/{id}<br>await _user_sf.invalidate(user_id)  # push-based invalidation</pre><blockquote><strong><em>How long should TTL be?</em></strong><em> As long as your “acceptable staleness.” Typical 10–60s. For transactional data, keep TTL short and always invalidate on writes.</em></blockquote><h3>Hands-on 3: Shared cache with Redis + pub/sub invalidation</h3><p>In-memory caches only help <strong>within</strong> a single process. For multiple Uvicorn workers or multiple pods, use Redis. Combine it with <strong>pub/sub invalidation</strong> to broadcast evictions.</p><pre># app/cache/redis_cache.py<br>import json, time, asyncio<br>from typing import Any, Callable, Awaitable<br>import redis.asyncio as redis  # redis&gt;=4 ships asyncio API<br><br>class RedisTTLCache:<br>    &quot;&quot;&quot;Shared cache backed by Redis; with local front cache for speed.&quot;&quot;&quot;<br>    def __init__(self, redis_url: str, ttl: int = 30) -&gt; None:<br>        self.ttl = ttl<br>        self._r = redis.from_url(redis_url, decode_responses=True)<br>        self._local: dict[str, tuple[float, Any]] = {}  # (exp_ts, value)<br>        self._locks: dict[str, asyncio.Lock] = {}<br>        self._channel = &quot;cache_invalidate&quot;<br>    async def get(self, key: str, fetcher: Callable[[], Awaitable[Any]]) -&gt; Any:<br>        now = time.monotonic()<br>        local = self._local.get(key)<br>        if local and local[0] &gt; now:<br>            return local[1]<br>        # Try Redis first<br>        val = await self._r.get(key)<br>        if val is not None:<br>            obj = json.loads(val)<br>            self._local[key] = (now + self.ttl, obj)<br>            return obj<br>        # Single-flight per key (process-local)<br>        lock = self._locks.setdefault(key, asyncio.Lock())<br>        async with lock:<br>            local = self._local.get(key)<br>            if local and local[0] &gt; time.monotonic():<br>                return local[1]<br>            obj = await fetcher()<br>            await self._r.set(key, json.dumps(obj), ex=self.ttl)<br>            self._local[key] = (time.monotonic() + self.ttl, obj)<br>            return obj<br>    async def invalidate(self, key: str) -&gt; None:<br>        await self._r.delete(key)<br>        await self._r.publish(self._channel, key)<br>        self._local.pop(key, None)<br>    async def subscribe_invalidation(self) -&gt; None:<br>        &quot;&quot;&quot;Listen for invalidation events to drop local front cache.&quot;&quot;&quot;<br>        pubsub = self._r.pubsub()<br>        await pubsub.subscribe(self._channel)<br>        async for msg in pubsub.listen():<br>            if msg.get(&quot;type&quot;) == &quot;message&quot;:<br>                key = msg[&quot;data&quot;]<br>                self._local.pop(key, None)</pre><p>Usage (all workers drop their local front cache on invalidation):</p><pre># app/services/catalog.py<br>CATALOG_TTL = 60<br>redis_cache = RedisTTLCache(&quot;redis://localhost:6379/0&quot;, ttl=CATALOG_TTL)<br><br>async def get_catalog() -&gt; dict:<br>    async def fetch():<br>        # Heavy DB aggregation here...<br>        return {&quot;items&quot;: [...], &quot;updated_at&quot;: &quot;...&quot;}<br>    return await redis_cache.get(&quot;catalog:v1&quot;, fetch)<br><br># after POST/PUT that modifies the catalog:<br>await redis_cache.invalidate(&quot;catalog:v1&quot;)</pre><blockquote><em>In production, run </em><em>subscribe_invalidation() in a background task (FastAPI lifespan/on_startup). Any node that writes triggers an invalidation; </em><strong><em>all nodes</em></strong><em> drop their front cache immediately.</em></blockquote><h3>Hands-on 4: HTTP caching (ETag / Cache-Control) and client disk cache</h3><p>Even without Redis, HTTP caching gives substantial wins.</p><pre># app/api/catalog.py (FastAPI)<br>import hashlib<br>from fastapi import APIRouter, Request, Response<br><br>router = APIRouter()<br>def _etag(content: bytes) -&gt; str:<br>    return hashlib.sha256(content).hexdigest()<br>@router.get(&quot;/catalog&quot;)<br>async def catalog(request: Request):<br>    # Typically you&#39;d build this from Redis/DB first<br>    data = b&#39;{&quot;items&quot;:[...]}&#39;<br>    tag = _etag(data)<br>    if request.headers.get(&quot;if-none-match&quot;) == tag:<br>        return Response(status_code=304, headers={&quot;ETag&quot;: tag})<br>    return Response(<br>        content=data,<br>        media_type=&quot;application/json&quot;,<br>        headers={<br>            &quot;ETag&quot;: tag,<br>            &quot;Cache-Control&quot;: &quot;public, max-age=60&quot;,<br>        },<br>    )</pre><p>Client-side and scripting are easy with requests-cache:</p><pre># pip install requests-cache<br>import requests<br>import requests_cache<br><br>requests_cache.install_cache(&quot;http_cache&quot;, expire_after=60)<br>def fetch(url: str) -&gt; dict:<br>    &quot;&quot;&quot;Within TTL, responses come from local SQLite cache.&quot;&quot;&quot;<br>    r = requests.get(url, timeout=5)<br>    r.raise_for_status()<br>    return r.json()</pre><blockquote><em>A CDN/reverse proxy (e.g., Cloudflare or NGINX) amplifies these benefits. For static assets, use long-lived, versioned URLs with </em><em>immutable caching semantics.</em></blockquote><h3>Hands-on 5: cached_property for one-time heavy resources</h3><p>Great for template engines, compiled regexes, ML models, or connection factories.</p><pre>from functools import cached_property<br>import re<br>from jinja2 import Environment, PackageLoader, select_autoescape<br><br>class Renderer:<br>    &quot;&quot;&quot;Heavy resources built once per instance.&quot;&quot;&quot;<br>    @cached_property<br>    def env(self) -&gt; Environment:<br>        # Construct once, reuse forever<br>        return Environment(<br>            loader=PackageLoader(&quot;app&quot;, &quot;templates&quot;),<br>            autoescape=select_autoescape()<br>        )<br>    @cached_property<br>    def phone_re(self):<br>        return re.compile(r&quot;\+?886-?\d{9,10}&quot;)<br>    def render_user(self, user: dict) -&gt; str:<br>        if not self.phone_re.match(user[&quot;phone&quot;]):<br>            raise ValueError(&quot;invalid phone&quot;)<br>        tpl = self.env.get_template(&quot;user.html.j2&quot;)<br>        return tpl.render(user=user)</pre><h3>Containers and __pycache__</h3><ul><li><strong>Super clean image</strong>: avoid layer churn<br>dockerfile ENV PYTHONDONTWRITEBYTECODE=1</li><li><strong>Faster startup</strong>: centralize .pyc into a volatile path<br>dockerfile ENV PYTHONPYCACHEPREFIX=/var/cache/pycache VOLUME /var/cache/pycache</li></ul><p>JetBrains/IDEA often runs with -X pycache_prefix=... to keep .pyc out of your repo. That does <strong>not</strong> affect program semantics.</p><h3>Test hygiene</h3><pre># tests/conftest.py<br>import pytest<br>from app.core.settings import get_settings<br>from app.services.users import _user_sf  # your single-flight cache<br><br>@pytest.fixture(autouse=True)<br>def _clear_caches():<br>    &quot;&quot;&quot;Ensure isolation between tests.&quot;&quot;&quot;<br>    get_settings.cache_clear()<br>    yield<br>    get_settings.cache_clear()<br>    # Invalidate in-memory TTL caches too<br>    import asyncio<br>    asyncio.get_event_loop().run_until_complete(_user_sf.invalidate())</pre><p>If you use Redis in production, swap in a containerized Redis for integration tests, or inject an in-memory stub to keep tests deterministic.</p><h3>Observability &amp; SLOs</h3><p>Export at least:</p><ul><li><strong>hit_ratio</strong>: hits / (hits + misses)</li><li><strong>fetch_latency</strong>: latency of the source on misses (DB/API)</li><li><strong>error_rate</strong>: how caches behave when the source errors (serve stale?)</li><li><strong>keyspace<em>size / memory</em>usage</strong>: current cache size</li></ul><p>Prometheus example (conceptual; implement with prometheus_client):</p><pre>from prometheus_client import Counter, Histogram<br><br>CACHE_HIT = Counter(&quot;cache_hit_total&quot;, &quot;Cache hits&quot;, [&quot;name&quot;])<br>CACHE_MISS = Counter(&quot;cache_miss_total&quot;, &quot;Cache misses&quot;, [&quot;name&quot;])<br>FETCH_LAT = Histogram(&quot;cache_fetch_seconds&quot;, &quot;Source fetch latency&quot;, [&quot;name&quot;])<br># In your cache wrapper:<br># - On hit: CACHE_HIT.labels(&quot;user_profile&quot;).inc()<br># - On miss: with FETCH_LAT.labels(&quot;user_profile&quot;).time(): fetch()<br># - After fetch: CACHE_MISS.labels(&quot;user_profile&quot;).inc()</pre><h3>Anti-patterns &amp; pitfalls</h3><ul><li><strong>TTL only, no invalidation</strong>: you will serve stale data after writes; always invalidate.</li><li><strong>Unbounded </strong><strong>@cache</strong>: can blow up memory when the key domain is large; prefer @lru_cache(maxsize=N).</li><li><strong>Mutable returns</strong>: mutating cached objects pollutes the cache; return immutable or copies.</li><li><strong>Multi-process/pod mismatch</strong>: in-memory caches don’t propagate; use Redis/Memcached.</li><li><strong>Stampedes</strong>: many keys expiring simultaneously; offset TTLs, use single-flight, preload, or stale-while-revalidate.</li><li><strong>Dirty tests</strong>: not clearing caches causes flaky tests.</li><li><strong>Long tail keys</strong>: sparse keys dilute hit ratio; evaluate whether caching helps and tune maxsize.</li></ul><h3>Pocket checklist</h3><p>1) <strong>Read-heavy, okay with 10–60s staleness?</strong><br>→ Single-Flight + TTL; add Redis + pub/sub across processes.</p><p>2) <strong>Write-heavy, strict consistency?</strong><br>→ Don’t cache core transactional rows; cache only derived or non-critical views (reports, catalogs, settings).</p><p>3) <strong>Large/static responses?</strong><br>→ ETag + Cache-Control; put a CDN in front.</p><p>4) <strong>Expensive object setup?</strong><br>→ cached_property.</p><p>5) <strong>Baseline</strong><br>→ @lru_cache(maxsize=1) on get_settings() — safe and instant.</p><h3>Appendix: Handy commands</h3><ul><li>Remove all .pyc under the project:<br>bash find . -type d -name __pycache__ -prune -exec rm -rf {} +</li><li>Disable bytecode for a run: python -B app.py or export PYTHONDONTWRITEBYTECODE=1</li><li>Centralize bytecode: python -X pycache_prefix=/tmp/pyc app.py or export PYTHONPYCACHEPREFIX=/tmp/pyc</li><li>Refresh import system after adding new files at runtime:<br>python import importlib; importlib.invalidate_caches()</li><li>pip cache: pip cache dir, pip cache purge</li></ul><h3>Closing</h3><p>Think of caching as three verbs: <strong>coalesce</strong> concurrent fetches (single-flight), <strong>retain</strong> for a reasonable period (TTL/ETag), and <strong>invalidate</strong>reliably (events). Start with @lru_cache and HTTP ETag for instant wins; then move your hottest paths to Single-Flight + Redis with metrics, so performance and stability rise together.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b51d4063ac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/the-practical-guide-to-python-caching-from-pycache-to-lru-ttl-single-flight-redis-and-http-28b51d4063ac">The Practical Guide to Python Caching: from __pycache__ to LRU/TTL/Single-Flight, Redis, and HTTP</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Alembic Shouts “Can’t locate revision …”: The Hidden Trap When OrbStack and Docker Desktop Run…]]></title>
            <link>https://medium.com/codecodecode/why-alembic-shouts-cant-locate-revision-the-hidden-trap-when-orbstack-and-docker-desktop-run-23c867f90ec0?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c867f90ec0</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[alembic]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[orbstack]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Wed, 01 Oct 2025 17:59:25 GMT</pubDate>
            <atom:updated>2025-10-01T17:59:25.231Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Alembic Shouts “Can’t locate revision …”: The Hidden Trap When OrbStack and Docker Desktop Run Together</h3><h3>Why Alembic Shouts “Can’t locate revision …”: The Hidden Trap When OrbStack and Docker Desktop Run Together</h3><blockquote><strong><em>TL;DR</em></strong><em>: This isn’t an Alembic “cache” issue. Your app is connecting to the </em><strong><em>wrong Postgres instance</em></strong><em>, whose </em><em>alembic_versionstill points to a revision that no longer exists in your repository (e.g., </em><em>0997d75093b0). When </em><strong><em>OrbStack</em></strong><em> and </em><strong><em>Docker Desktop</em></strong><em> are both running, you can end up with </em><strong><em>two separate Postgres + volumes</em></strong><em> that look similar (same host/port), and your app silently hits the older one. Alembic then tries to resolve a DB head that </em><strong><em>isn’t present</em></strong><em> in your </em><em>alembic/versions/ anymore and fails with:</em></blockquote><pre>alembic.util.exc.CommandError: Can&#39;t locate revision identified by &#39;0997d75093b0&#39;</pre><h3>The Story: “I deleted my migrations, why is the error still here?”</h3><p>You boot FastAPI/Uvicorn. A bootstrap step triggers migrations. Suddenly:</p><pre>alembic.util.exc.CommandError: Can&#39;t locate revision identified by &#39;0997d75093b0&#39;</pre><p>You even cleared alembic/versions/ and __pycache__, but the error persists. The twist: it <strong>only</strong> happens when <strong>both OrbStack <em>and</em> Docker Desktop</strong> are open. That’s the telltale sign that you’re not talking to the DB you think you are.</p><h3>Background: How Alembic decides “which migrations to run”</h3><ul><li>Before running, Alembic queries the database for its current head from <strong>alembic_version</strong> (or multiple heads in multi-head scenarios).</li><li>Then it builds a <strong>revision graph</strong> from the migration files in your repository (alembic/versions/).</li><li>If the <strong>DB’s recorded head doesn’t exist in the filesystem</strong>, Alembic can’t walk the graph and throws <strong>“Can’t locate revision …”</strong>.</li></ul><p>So the root cause is <strong>DB ↔ repository mismatch</strong>, not stale caches.</p><h3>Why running OrbStack and Docker Desktop makes this more likely</h3><ul><li>Each runtime maintains <strong>different Docker contexts, networks, and volumes</strong>.</li><li>Your innocent postgres://localhost:5432 might point to <strong>different Postgres instances</strong> under different contexts.</li><li>If both sides happen to bind 5432 (or your compose files don’t pin ports uniquely), the app can <strong>silently</strong> hit the <em>old</em> DB with an <em>old</em>volume.</li><li>That old volume’s alembic_version could still be 0997d75093b0, while your repo no longer contains that migration script → <strong>boom</strong>.</li></ul><h3>A 3‑Minute Triage Checklist (practical and effective)</h3><p><strong>1) Ensure your CLI is talking to the intended Docker context</strong></p><pre>docker context ls<br>docker context use desktop-linux   # or: docker context use orbstack</pre><p><strong>2) Who is listening on 5432? (detect conflicts and origins)</strong></p><pre>lsof -iTCP:5432 -sTCP:LISTEN -nP<br># Check whether the listener is from orbstack or docker-desktop</pre><p><strong>3) Ask the DB directly: what’s your Alembic head?</strong></p><pre>psql &quot;postgresql://USER:PASS@localhost:5432/DBNAME&quot; \<br>  -c &quot;select * from alembic_version;&quot;<br># If you see 0997d75093b0, you’re on the old volume/instance.</pre><blockquote><em>Pro tip: If you change your compose’s exposed port (see next section), try </em><em>psql against that port so you </em><strong><em>know</em></strong><em> which instance you’re hitting.</em></blockquote><h3>Fix Strategies (choose the one that fits your current goal)</h3><h3>A) Keep your migration files as the source of truth, align the DB (safe &amp; common)</h3><ol><li><strong>Run only one runtime</strong> (close the other, or pin docker context use).</li><li>Ensure alembic/versions/ contains the baseline/head you expect.</li><li>On the <strong>correct DB instance</strong>, run:</li></ol><pre># If this DB should be treated as &quot;fresh&quot; w.r.t. the current repo state:<br>alembic stamp head<br>alembic upgrade head</pre><blockquote><em>stamp head sets the DB’s version to your repo’s current head </em><strong><em>without</em></strong><em> running historical diffs. Then </em><em>upgrade head applies any pending steps.</em></blockquote><h3>B) Clean-room dev reset: drop the data volume and rebuild (fastest for dev)</h3><p><strong>This deletes data — dev environments only.</strong></p><pre>docker compose down -v    # remove volumes (data will be wiped)<br>docker compose up -d<br>alembic upgrade head</pre><h3>C) Quick unblocking: unpin the “unknown” revision and move forward</h3><pre># Treat DB as having no revision<br>alembic stamp base<br># Then bring it up to date<br>alembic upgrade head</pre><blockquote><em>Use this if the schema/data aren’t important, or you’re fine treating the DB as freshly initialized.</em></blockquote><h3>Long‑Term Guardrails (a.k.a. how to stop this from ever happening again)</h3><h3>1) Pin a single Docker context</h3><p>Pin it at the top of your Makefile or bootstrap scripts:</p><pre>docker context use desktop-linux   # or: docker context use orbstack</pre><p>Or set it in your shell init so you don’t flip-flop unintentionally.</p><h3>2) Avoid port 5432 collisions (highly recommended)</h3><p>Give your dev Postgres a <strong>unique host port</strong> so you always know which instance you’re hitting:</p><pre># docker-compose.yml<br>services:<br>  db:<br>    image: postgres:16<br>    ports:<br>      - &quot;55432:5432&quot;   # use 55432 externally</pre><p>Then point your app/DSN to localhost:55432. Even if both runtimes are up, you’ll always land on <strong>this</strong> instance.</p><h3>3) Fix the Compose project and volume names</h3><p>In a .env or compose file:</p><pre>COMPOSE_PROJECT_NAME=remote_lock_cloud_dev</pre><p>And give volumes <strong>distinct, explicit names</strong> to avoid “same-looking name, different runtime” confusion.</p><h3>4) Fail‑fast sanity check before running migrations (strongly recommended)</h3><p>Before running migrations, verify that the DB head(s) exist in the repo. Example utility (comments in English by design):</p><pre># app/services/db_migration_sanity.py<br>from alembic.config import Config<br>from alembic.script import ScriptDirectory<br>from alembic.runtime.migration import MigrationContext<br><br>def assert_db_heads_are_known(engine, alembic_cfg: Config):<br>    &quot;&quot;&quot;<br>    Fail fast if the DB points to unknown Alembic heads.<br>    &quot;&quot;&quot;<br>    script = ScriptDirectory.from_config(alembic_cfg)<br>    known = {rev.revision for rev in script.walk_revisions()}<br>    with engine.connect() as conn:<br>        ctx = MigrationContext.configure(conn)<br>        current_heads = set(ctx.get_current_heads())<br>    unknown = current_heads - known<br>    if unknown:<br>        raise RuntimeError(<br>            f&quot;DB has unknown Alembic heads: {unknown}. &quot;<br>            &quot;Likely connected to the wrong database or missing migration files.&quot;<br>        )</pre><p>Wiring it into your bootstrap:</p><pre>if settings.AUTO_MIGRATE:<br>    assert_db_heads_are_known(engine, cfg)  # fail fast with a clear message<br>    run_db_migrations()</pre><h3>5) Gate revision --autogenerate behind a flag</h3><p>Daily runs should <strong>only</strong> do upgrade. Generate new revisions <strong>only</strong> when explicitly requested:</p><pre>AUTO_GENERATE_REVISION=1 make dev   # otherwise skip autogenerate</pre><h3>Common Pitfalls (and why they’re wrong)</h3><ul><li><strong>“Deleting </strong><strong>alembic/versions/ will fix it.”</strong><br>No. The DB’s alembic_version still points to an old revision. If the repo can’t see that revision, Alembic will complain — by design.</li><li><strong>“This must be an Alembic cache bug.”</strong><br>It isn’t. The core problem is <strong>mismatch</strong> between the database’s recorded state and the repository’s migration graph.</li><li><strong>“Hot reload (WatchFiles/Uvicorn) is causing this.”</strong><br>Hot reload affects code loading, not <strong>which Postgres instance</strong> you connect to.</li></ul><h3>A Simple Decision Tree</h3><ul><li><strong>Dev only, data can be wiped</strong> → <strong>Strategy B</strong> (clean reset).</li><li><strong>Keep data, treat DB as aligned to current repo now</strong> → <strong>Strategy A</strong> (stamp head → upgrade head).</li><li><strong>Just unblock quickly; data not important</strong> → <strong>Strategy C</strong> (stamp base → upgrade head).</li></ul><h3>Final Thoughts: Keep the problem outside the door</h3><p>“Can’t locate revision …” errors are symptoms of <strong>environment consistency</strong> problems. Lock down your Docker context, ports, and volumes; add a fail‑fast preflight check; and gate autogeneration behind a flag. Next time you see:</p><pre>Can&#39;t locate revision identified by &#39;0997d75093b0&#39;</pre><p>Don’t delete files. <strong>Ask your DB who it is</strong> — then fix the mismatch with intent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c867f90ec0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/why-alembic-shouts-cant-locate-revision-the-hidden-trap-when-orbstack-and-docker-desktop-run-23c867f90ec0">Why Alembic Shouts “Can’t locate revision …”: The Hidden Trap When OrbStack and Docker Desktop Run…</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build “Plug-In” Powers with Python Mixins: A Practical, Fun, and Thorough Guide]]></title>
            <link>https://medium.com/codecodecode/build-plug-in-powers-with-python-mixins-a-practical-fun-and-thorough-guide-f3cef0c60499?source=rss-ee0a0984445a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3cef0c60499</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[mixin]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Chris Evans]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 10:55:16 GMT</pubDate>
            <atom:updated>2025-09-29T10:55:16.326Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Mixins let you add small, reusable superpowers to your classes — without turning your codebase into a tangled inheritance jungle.</em></blockquote><p>This article is packed with <strong>real examples</strong> you can paste into your projects. We’ll cover what Mixins are, when (and when not) to use them, how they compare to other design options, and plenty of patterns you’ll reuse forever.</p><h3>TL;DR</h3><ul><li><strong>What</strong>: A <strong>mixin</strong> is a small class meant to be inherited from to add focused capabilities (logging, JSON, timestamps…), not to stand on its own.</li><li><strong>Why</strong>: Horizontal reuse without bloating your business classes or creating deep inheritance trees.</li><li><strong>How</strong>: Keep them small, stateless or minimally stateful, use <strong>cooperative </strong><strong>super()</strong>, and avoid coupling to specific bases.</li><li><strong>When not</strong>: If you only need to enhance a <strong>single instance</strong> → use a <strong>decorator</strong>. If you need a <strong>clear boundary</strong> and runtime substitution → use <strong>composition</strong>.</li><li><strong>Bonus</strong>: Protocols/ABCs define <strong>capabilities</strong>, Mixins provide <strong>default implementations</strong>.</li></ul><h3>What is a Mixin — Really?</h3><p>A <strong>mixin</strong> is a class designed to be inherited alongside your “real” class to gift it a discrete, reusable ability (e.g., to_json(), logger, soft_delete()). It should: - Have <strong>one job</strong>, - Be <strong>safe to combine</strong> with other mixins, - Avoid heavy __init__ or deep assumptions about parents, - Be named like SomethingMixin.</p><h3>Design Principles (Battle-Tested)</h3><ul><li><strong>Single Responsibility</strong>: One capability per mixin.</li><li><strong>Cooperative </strong><strong>super()</strong>: If a mixin overrides a method others might also override, call super() so the <strong>MRO chain</strong> stays intact.</li><li><strong>Minimal State</strong>: Prefer methods over state. If you must store state, do it clearly and consistently.</li><li><strong>No Hidden Parents</strong>: Don’t assume a specific base class unless you document it (or enforce via ABC).</li><li><strong>Clear Overridable Hooks</strong>: Expose _before_*/_after_* hooks to let other mixins chain behaviors.</li><li><strong>Test in Isolation + In Combination</strong>: Unit test the mixin itself; add integration tests when stacked.</li></ul><h3>Mixins vs Other Designs (How to Choose)</h3><p>ScenarioPrefer“All instances of this class should get a new capability.”<strong>Mixin</strong>“Only this one instance needs a temporary wrapper behavior.”<strong>Decorator</strong>“We need a clear boundary and runtime substitution.”<strong>Composition</strong>“We need a type/behavior contract without inheritance coupling.”<strong>Protocol / ABC</strong>“We need vertical specialization with rich semantics.”<strong>Classic inheritance</strong> (but prefer composition first)</p><h3>A Reusable Starter Pack (Copy-Paste Friendly)</h3><p>Below is a <strong>modular toolkit</strong>. Use what you need, delete the rest. All comments are in English.</p><h3>1) JSON Serialization</h3><pre>import json<br>from dataclasses import asdict, is_dataclass<br>from typing import Iterable, Mapping, Optional, Set<br><br>class JsonSerializableMixin:<br>    &quot;&quot;&quot;Provide to_json() with optional field filtering.&quot;&quot;&quot;<br>    _json_exclude: Set[str] = set()<br>    def to_dict(self) -&gt; Mapping:<br>        if is_dataclass(self):<br>            data = asdict(self)<br>        else:<br>            data = dict(getattr(self, &quot;__dict__&quot;, {}))<br>        for k in list(data.keys()):<br>            if k in self._json_exclude:<br>                data.pop(k, None)<br>        return data<br>    def to_json(self, *, ensure_ascii: bool = False, indent: Optional[int] = None) -&gt; str:<br>        return json.dumps(self.to_dict(), ensure_ascii=ensure_ascii, indent=indent)</pre><p><strong>Usage:</strong></p><pre>from dataclasses import dataclass<br>from typing import ClassVar, Set<br><br><br>@dataclass<br>class User(JsonSerializableMixin):<br>    # Fields<br>    name: str<br>    email: str<br>    password: str<br><br>    # Fields to exclude when serializing to JSON<br>    jsonexclude: ClassVar[Set[str]] = {&quot;password&quot;}<br><br><br>print(User(&quot;Chris&quot;, &quot;c@example.com&quot;, &quot;secret&quot;).to_json(indent=2))</pre><h3>2) Logging (namespaced per class)</h3><pre>import logging<br><br>class LoggingMixin:<br>    &quot;&quot;&quot;Attach a namespaced logger.&quot;&quot;&quot;<br>    @property<br>    def logger(self) -&gt; logging.Logger:<br>        return logging.getLogger(f&quot;{self.__class__.__module__}.{self.__class__.__name__}&quot;)</pre><p><strong>Usage:</strong></p><pre>class OrderService(LoggingMixin):<br>    def create(self, payload: dict) -&gt; None:<br>        self.logger.info(<br>            &quot;Creating order&quot;,<br>            extra={&quot;payload&quot;: payload}<br>        )</pre><h3>3) Permission Checking (tiny + duck-typed)</h3><pre>from typing import Iterable<br><br>class PermissionRequiredMixin:<br>    &quot;&quot;&quot;Check a &#39;permissions&#39; iterable on the given user object.&quot;&quot;&quot;<br>    def has_permission(self, user, permission: str) -&gt; bool:<br>        perms: Iterable[str] = getattr(user, &quot;permissions&quot;, [])<br>        return permission in perms</pre><p><strong>Usage:</strong></p><pre>class PermissionRequiredMixin:<br>    def has_permission(self, user, permission: str) -&gt; bool:<br>        return permission in getattr(user, &quot;permissions&quot;, [])<br><br><br>class Document(PermissionRequiredMixin):<br>    def __init__(self, content: str) -&gt; None:<br>        self.content = content<br><br><br>user = type(&quot;User&quot;, (), {&quot;permissions&quot;: [&quot;read&quot;]})()<br><br>assert Document(&quot;secret&quot;).has_permission(user, &quot;read&quot;)</pre><p><strong>Composition alternative</strong>: Pass a PermissionService into your class if you need complex checks.</p><h3>4) Timestamps &amp; Soft Delete (framework-agnostic)</h3><pre>from datetime import datetime<br>from typing import Optional<br><br>class TimestampMixin:<br>    &quot;&quot;&quot;Add created_at/updated_at and a touch() method.&quot;&quot;&quot;<br>    created_at: Optional[datetime] = None<br>    updated_at: Optional[datetime] = None<br>    def touch(self) -&gt; None:<br>        now = datetime.utcnow()<br>        if self.created_at is None:<br>            self.created_at = now<br>        self.updated_at = now<br>class SoftDeleteMixin:<br>    &quot;&quot;&quot;Mark entities as deleted without removal.&quot;&quot;&quot;<br>    deleted_at: Optional[datetime] = None<br>    def soft_delete(self) -&gt; None:<br>        self.deleted_at = datetime.utcnow()</pre><h3>5) SQLAlchemy 2.0-style Declarative Mixins (bonus)</h3><blockquote><em>If you use SQLAlchemy, you can expose columns and defaults via mixins.</em></blockquote><pre># pip install sqlalchemy&gt;=2.0<br>from __future__ import annotations<br>from datetime import datetime<br>from typing import Optional<br>from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column<br>from sqlalchemy import DateTime, func<br><br>class Base(DeclarativeBase):<br>    pass<br>class IdTimestampMixin:<br>    &quot;&quot;&quot;Provide id + audited timestamps.&quot;&quot;&quot;<br>    id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)<br>    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())<br>    updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), onupdate=func.now(), server_default=func.now())<br>class SoftDeleteOrmMixin:<br>    deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)<br>from sqlalchemy.orm import Mapped, mapped_column<br>class Note(IdTimestampMixin, SoftDeleteOrmMixin, Base):<br>    __tablename__ = &quot;notes&quot;<br>    body: Mapped[str] = mapped_column()</pre><h3>6) Retry Utility (as a mixin) + Decorator Contrast</h3><pre>import time<br>from typing import Callable, TypeVar<br><br>T = TypeVar(&quot;T&quot;)<br>class RetryMixin:<br>    &quot;&quot;&quot;Provide a simple retry_call utility.&quot;&quot;&quot;<br>    def retry_call(self, fn: Callable[..., T], *args, times: int = 3, delay: float = 0.1, **kwargs) -&gt; T:<br>        last = None<br>        for _ in range(times):<br>            try:<br>                return fn(*args, **kwargs)<br>            except Exception as e:<br>                last = e<br>                time.sleep(delay)<br>        raise last</pre><p><strong>Decorator alternative (instance-specific):</strong></p><pre>import time<br>from functools import wraps<br>from typing import Callable, TypeVar, Any<br><br>F = TypeVar(&quot;F&quot;, bound=Callable[..., Any])<br><br>def retry(times: int = 3, delay: float = 0.1) -&gt; Callable[[F], F]:<br>    &quot;&quot;&quot;<br>    Retry a function up to `times` with a fixed `delay` (seconds) between attempts.<br>    Re-raises the last exception if all attempts fail.<br>    &quot;&quot;&quot;<br>    if times &lt; 1:<br>        raise ValueError(&quot;times must be &gt;= 1&quot;)<br>    if delay &lt; 0:<br>        raise ValueError(&quot;delay must be &gt;= 0&quot;)<br><br>    def _wrap(fn: F) -&gt; F:<br>        @wraps(fn)<br>        def _inner(*args: Any, **kwargs: Any) -&gt; Any:<br>            last_exc: Exception | None = None<br>            for attempt in range(1, times + 1):<br>                try:<br>                    return fn(*args, **kwargs)<br>                except Exception as e:<br>                    last_exc = e<br>                    if attempt == times:<br>                        # Out of attempts, re-raise the last exception<br>                        raise<br>                    time.sleep(delay)<br>            # Should not reach here, but keep mypy happy<br>            assert last_exc is not None<br>            raise last_exc<br>        return _inner  # type: ignore[return-value]<br>    return _wrap</pre><p>Choose <strong>mixin</strong> if many methods need retry as a tool; choose <strong>decorator</strong> if you only need to tag a few methods.</p><h3>7) Rate Limiting (tiny sliding window)</h3><pre>from collections import deque<br>from time import monotonic<br><br>class RateLimitMixin:<br>    &quot;&quot;&quot;Allow at most &#39;limit&#39; calls per &#39;window_seconds&#39;.&quot;&quot;&quot;<br>    def __init__(self, *a, limit: int = 5, window_seconds: float = 1.0, **kw):<br>        super().__init__(*a, **kw)<br>        self._rl_limit = limit<br>        self._rl_window = window_seconds<br>        self._rl_hits = deque()  # store monotonic timestamps<br>    def _rate_limit_check(self) -&gt; None:<br>        now = monotonic()<br>        while self._rl_hits and (now - self._rl_hits[0]) &gt; self._rl_window:<br>            self._rl_hits.popleft()<br>        if len(self._rl_hits) &gt;= self._rl_limit:<br>            raise RuntimeError(&quot;Rate limit exceeded&quot;)<br>        self._rl_hits.append(now)</pre><p><strong>Usage:</strong></p><pre>import time<br><br><br>class RateLimitMixin:<br>    &quot;&quot;&quot;Very small rate-limit mixin: allow 1 call per _min_interval seconds.&quot;&quot;&quot;<br>    _last_call_ts: float = 0.0<br>    _min_interval: float = 0.5  # seconds<br><br>    def _rate_limit_check(self) -&gt; None:<br>        now = time.time()<br>        if now - self._last_call_ts &lt; self._min_interval:<br>            raise RuntimeError(&quot;Rate limit exceeded&quot;)<br>        self._last_call_ts = now<br><br><br>class API(RateLimitMixin):<br>    def call(self) -&gt; str:<br>        self._rate_limit_check()<br>        return &quot;ok&quot;<br><br><br># Demo<br>api = API()<br>print(api.call())  # ok<br>try:<br>    print(api.call())  # raises<br>except RuntimeError as e:<br>    print(&quot;blocked:&quot;, e)<br><br>time.sleep(0.6)<br>print(api.call())  # ok again</pre><p>Make sure to <strong>call </strong><strong>super().__init__()</strong> in subclasses if they override __init__.</p><h3>8) Per-Instance Memoization (safe for unhashable self)</h3><pre>from functools import wraps<br><br>class MemoizeMixin:<br>    &quot;&quot;&quot;Cache method results per-instance using a dict on self.&quot;&quot;&quot;<br>    def _memoize(self, key, fn, *args, **kwargs):<br>        cache = getattr(self, &quot;_memo&quot;, None)<br>        if cache is None:<br>            cache = self._memo = {}<br>        if key not in cache:<br>            cache[key] = fn(*args, **kwargs)<br>        return cache[key]<br>    @staticmethod<br>    def memoize_method(fn):<br>        @wraps(fn)<br>        def wrapper(self, *a, **kw):<br>            key = (fn.__name__, a, tuple(sorted(kw.items())))<br>            return self._memoize(key, fn, *a, **kw)<br>        return wrapper</pre><p><strong>Usage:</strong></p><pre>from functools import lru_cache, wraps<br><br><br>class MemoizeMixin:<br>    @staticmethod<br>    def memoize_method(fn):<br>        # Use lru_cache; key includes `self`, so cache is per-instance naturally.<br>        cached = lru_cache(maxsize=None)(fn)<br><br>        @wraps(fn)<br>        def wrapper(self, *args, **kwargs):<br>            return cached(self, *args, **kwargs)<br><br>        # Expose cache utilities<br>        wrapper.cache_clear = cached.cache_clear<br>        wrapper.cache_info = cached.cache_info<br>        return wrapper<br><br><br>class Stats(MemoizeMixin):<br>    @MemoizeMixin.memoize_method<br>    def expensive(self, n: int) -&gt; int:<br>        # Pretend this is slow<br>        return sum(range(n))<br><br><br>s = Stats()<br>assert s.expensive(10_000_000) == s.expensive(10_000_000)</pre><h3>9) Hook/Template Mixins with Cooperative super()</h3><pre>class SaveHookMixin:<br>    &quot;&quot;&quot;Wrap save() with before/after hooks, using cooperative super().&quot;&quot;&quot;<br>    def save(self):<br>        self._before_save()<br>        result = super().save()<br>        self._after_save()<br>        return result<br><br>    def _before_save(self): ...<br>    def _after_save(self): ...<br><br>class AuditSaveMixin:<br>    def _before_save(self):<br>        print(&quot;audit before&quot;)<br>        super()._before_save()<br><br>class BaseRepo:<br>    def save(self):<br>        print(&quot;base save&quot;)<br><br>class Repo(AuditSaveMixin, SaveHookMixin, BaseRepo):<br>    pass<br><br>Repo().save()<br># audit before<br># base save</pre><p><strong>MRO tip</strong>:</p><pre>print(Repo.__mro__)</pre><h3>10) Validation + ABC/Protocol Combo</h3><pre>from abc import ABC, abstractmethod<br><br>class ValidatableMixin(ABC):<br>    &quot;&quot;&quot;Provide a template for validate().&quot;&quot;&quot;<br>    @abstractmethod<br>    def validate(self) -&gt; None:<br>        &quot;&quot;&quot;Raise ValueError if invalid.&quot;&quot;&quot;<br>class Customer(ValidatableMixin):<br>    def __init__(self, email: str):<br>        self.email = email<br>    def validate(self) -&gt; None:<br>        if &quot;@&quot; not in self.email:<br>            raise ValueError(&quot;Invalid email&quot;)</pre><p><strong>Protocol for capability without inheritance</strong>:</p><pre>from typing import Protocol, runtime_checkable<br><br><br>@runtime_checkable<br>class JsonLike(Protocol):<br>    def to_json(self) -&gt; str:  # protocol method signature<br>        ...<br><br><br>def dump(obj: JsonLike) -&gt; str:<br>    return obj.to_json()<br><br><br># --- demo ---<br>class User:<br>    def __init__(self, name: str) -&gt; None:<br>        self.name = name<br><br>    def to_json(self) -&gt; str:<br>        return f&#39;{{&quot;name&quot;: &quot;{self.name}&quot;}}&#39;<br><br><br>u = User(&quot;Chris&quot;)<br>print(dump(u))  # {&quot;name&quot;: &quot;Chris&quot;}</pre><p>Use <strong>Protocol</strong> to accept “anything with to_json()” (duck typing + type checking), and <strong>Mixins</strong> to provide a default implementation.</p><h3>11) Async Context Helpers</h3><pre>class AsyncClosingMixin:<br>    &quot;&quot;&quot;Guarantee &#39;close()&#39; on __aexit__ if present.&quot;&quot;&quot;<br>    async def __aenter__(self):<br>        return self<br><br>    async def __aexit__(self, exc_type, exc, tb):<br>        close = getattr(self, &quot;close&quot;, None)<br>        if callable(close):<br>            result = close()<br>            if hasattr(result, &quot;__await__&quot;):<br>                await result</pre><h3>12) Thread-Safety Guard (simple lock mixin)</h3><pre>from threading import RLock<br>from contextlib import contextmanager<br><br>class LockingMixin:<br>    &quot;&quot;&quot;Provide a re-entrant lock and a with_lock() helper.&quot;&quot;&quot;<br>    def __init__(self, *a, **kw):<br>        super().__init__(*a, **kw)<br>        self._lock = RLock()<br>    @contextmanager<br>    def with_lock(self):<br>        self._lock.acquire()<br>        try:<br>            yield<br>        finally:<br>            self._lock.release()</pre><p><strong>Usage:</strong></p><pre>class Counter(LockingMixin): def init(self): super().init() self.value = 0<br><br>def inc(self):<br>    with self.with_lock():<br>        self.value += 1</pre><h3>13) Rich `__repr__` / Equality Mixins</h3><pre>class ReprMixin:<br>    &quot;&quot;&quot;Readable repr using class name and public attributes.&quot;&quot;&quot;<br>    def __repr__(self) -&gt; str:<br>        attrs = &quot;, &quot;.join(f&quot;{k}={v!r}&quot; for k, v in self.__dict__.items() if not k.startswith(&quot;_&quot;))<br>        return f&quot;{self.__class__.__name__}({attrs})&quot;<br>class EqualityByAttrsMixin:<br>    &quot;&quot;&quot;Equality by comparing public attributes.&quot;&quot;&quot;<br>    def __eq__(self, other) -&gt; bool:<br>        if self.__class__ is not other.__class__:<br>            return NotImplemented<br>        a = {k: v for k, v in self.__dict__.items() if not k.startswith(&quot;_&quot;)}<br>        b = {k: v for k, v in other.__dict__.items() if not k.startswith(&quot;_&quot;)}<br>        return a == b<br>    def __hash__(self):<br>        # Caution: only hash if immutable; else remove __hash__<br>        return hash(tuple(sorted((k, repr(v)) for k, v in self.__dict__.items() if not k.startswith(&quot;_&quot;))))</pre><h3>Common Pitfalls (and Fixes)</h3><ul><li><strong>Forgetting </strong><strong>super()</strong>: Breaks the chain. If your mixin overrides a method others might also override (e.g., save()), always call super().</li><li><strong>Too many responsibilities</strong>: Split into smaller mixins.</li><li><strong>Shadowing names</strong>: Use clear hook names (_before_save) and docstrings.</li><li><strong>Hidden dependencies</strong>: If your mixin needs id or session, document it or enforce via ABC.</li><li><strong>State explosion</strong>: Switch to composition if you’re adding many fields or complex lifecycles.</li></ul><h3>Quick Decision Checklist</h3><ol><li>Is the capability <strong>small and reused</strong> across many classes? → <strong>Mixin</strong>.</li><li>Do you only need to wrap <strong>one instance</strong> right now? → <strong>Decorator</strong>.</li><li>Do you need <strong>swappable strategies</strong> and clean boundaries? → <strong>Composition</strong>.</li><li>Do you need a <strong>contract</strong> others can implement without inheritance? → <strong>Protocol / ABC</strong>.</li><li>Will multiple mixins touch the <strong>same method</strong>? → Use <strong>cooperative </strong><strong>super()</strong> and hooks.</li></ol><h3>Closing Thoughts</h3><p>Mixins shine when you want to <strong>add small, horizontal capabilities</strong> everywhere: JSON, logging, permission checks, timestamps, soft delete, hooks, retry tools, rate limits, memoization, and more. Keep them <strong>small, composable, and well-documented</strong>. Pair them with <strong>decorators</strong> (for instance-level enhancements), <strong>composition</strong> (for swappable behavior), and <strong>Protocols/ABCs</strong> (for contracts) to build codebases that are <strong>clean, flexible, and friendly to change</strong>.</p><p>If you want, I can bundle these into a tiny “<strong>mixin-starter</strong>” repository with tests and a demo app — ready to drop into your stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3cef0c60499" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codecodecode/build-plug-in-powers-with-python-mixins-a-practical-fun-and-thorough-guide-f3cef0c60499">Build “Plug-In” Powers with Python Mixins: A Practical, Fun, and Thorough Guide</a> was originally published in <a href="https://medium.com/codecodecode">codecodecode</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>