<?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 KH Huang on Medium]]></title>
        <description><![CDATA[Stories by KH Huang on Medium]]></description>
        <link>https://medium.com/@joloiuy?source=rss-197c359c83d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nhBfCKvWjgyX9audkE7ZBw.png</url>
            <title>Stories by KH Huang on Medium</title>
            <link>https://medium.com/@joloiuy?source=rss-197c359c83d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:18:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joloiuy/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[Automated AsyncAPI Docs in Django: WebSocket Schemas Like Swagger]]></title>
            <link>https://medium.com/@joloiuy/automated-asyncapi-docs-in-django-websocket-schemas-like-swagger-21d5df74a8a4?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/21d5df74a8a4</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[asyncapi]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[schema]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Mon, 22 Dec 2025 11:53:52 GMT</pubDate>
            <atom:updated>2025-12-26T14:32:19.872Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oLXoPrbNm6AVSFr0" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@laurensauderstudio?utm_source=local&amp;utm_medium=referral"><em>Lauren Sauder</em></a><em> on </em><a href="https://unsplash.com/photos/1OUzxbySjlQ?utm_source=local&amp;utm_medium=referral"><em>Unsplash</em></a></figcaption></figure><p>Swagger-like docs for REST are easy. For WebSockets, it’s usually a README and wishful thinking.</p><p>If you’re building <strong>Django WebSocket APIs</strong>, AsyncAPI is the Swagger equivalent — you just need <strong>automated</strong> generation, not manual YAML.</p><p>This post shows how to <strong>automate AsyncAPI docs in Django</strong> so they feel like Swagger: schema-driven, discoverable, and always in sync with your handlers.</p><p>You’ll end up with: — A live HTML docs page — JSON/YAML spec endpoints — Automatic schema generation tied to your handlers</p><h3>Requirements (and what’s optional)</h3><p>You only need three pieces:</p><ul><li><strong>Django</strong> (routing + templates)</li><li><strong>A WebSocket layer</strong> (Channels or your own consumer abstraction)</li><li><strong>AsyncAPI renderer</strong> (official React component)</li></ul><p><strong>Pydantic is optional.</strong> It’s great for validation + JSON Schema, but any schema system works as long as you can emit JSON Schema.</p><h3>What we’re automating</h3><p>We want three things:</p><p>1) <strong>A decorator</strong> to register WebSocket message handlers 2) <strong>A generator</strong> that produces AsyncAPI JSON/YAML 3) <strong>A docs page</strong> that renders a live AsyncAPI UI</p><p>The model is simple: annotate handlers with request/response schemas, then <strong>auto-generate docs</strong> from those schemas.</p><h3>1) Define message schemas</h3><pre>from pydantic import BaseModel<br><br>class SubscribeRequest(BaseModel):<br>    channel: str<br><br>class PriceUpdate(BaseModel):<br>    channel: str<br>    price: float<br>    ts: int</pre><p>Use Pydantic (or any schema system) to define payloads. These become AsyncAPI message schemas.</p><h3>2) Add a decorator + registry</h3><p>This decorator does two jobs: — validates payloads at runtime — registers metadata for docs</p><pre>import functools<br>from pydantic import BaseModel<br><br>class MessageHandler:<br>    def __init__(self, message_type, func, request_schema=None, response_schema=None, description=None, tags=None):<br>        self.message_type = message_type<br>        self.func = func<br>        self.request_schema = request_schema<br>        self.response_schema = response_schema<br>        self.description = description or (func.__doc__ or &quot;&quot;)<br>        self.tags = tags or []<br>        functools.update_wrapper(self, func)<br><br>class AsyncAPIRegistry:<br>    handlers = {}  # consumer_name -&gt; message_type -&gt; MessageHandler<br><br>    @classmethod<br>    def register_handler(cls, consumer, message_type, handler):<br>        cls.handlers.setdefault(consumer, {})[message_type] = handler<br><br><br>def message_handler(message_type, request_schema=None, response_schema=None, description=None, tags=None):<br>    def decorator(func):<br>        handler = MessageHandler(message_type, func, request_schema, response_schema, description, tags)<br>        handler._is_message_handler = True<br>        handler._message_type = message_type<br>        return handler<br>    return decorator</pre><p>You can also add a @register_consumer class decorator to auto-register all handlers in a consumer class.</p><h3>3) Generate AsyncAPI from the registry</h3><pre>from urllib.parse import urlparse<br><br>class AsyncAPIGenerator:<br>    @classmethod<br>    def generate_spec(cls, title, version, description, server_url):<br>        parsed = urlparse(server_url)<br>        host = f&quot;{parsed.hostname}:{parsed.port}&quot; if parsed.port else parsed.hostname<br><br>        spec = {<br>            &quot;asyncapi&quot;: &quot;3.0.0&quot;,<br>            &quot;info&quot;: {&quot;title&quot;: title, &quot;version&quot;: version, &quot;description&quot;: description},<br>            &quot;servers&quot;: {&quot;production&quot;: {&quot;host&quot;: host, &quot;protocol&quot;: parsed.scheme or &quot;wss&quot;, &quot;pathname&quot;: parsed.path or &quot;/&quot;}},<br>            &quot;channels&quot;: {},<br>            &quot;operations&quot;: {},<br>            &quot;components&quot;: {&quot;schemas&quot;: {}, &quot;messages&quot;: {}},<br>        }<br><br>        for consumer_name, handlers in AsyncAPIRegistry.handlers.items():<br>            channel = spec[&quot;channels&quot;].setdefault(consumer_name, {<br>                &quot;address&quot;: f&quot;/{consumer_name}&quot;,<br>                &quot;description&quot;: f&quot;{consumer_name} WebSocket channel&quot;,<br>                &quot;messages&quot;: {},<br>            })<br><br>            for message_type, handler in handlers.items():<br>                if handler.request_schema:<br>                    cls._add_schema(spec, handler.request_schema, handler)<br>                    channel[&quot;messages&quot;][handler.request_schema.__name__] = {<br>                        &quot;$ref&quot;: f&quot;#/components/messages/{handler.request_schema.__name__}&quot;<br>                    }<br>                if handler.response_schema:<br>                    cls._add_schema(spec, handler.response_schema, handler)<br>                    channel[&quot;messages&quot;][handler.response_schema.__name__] = {<br>                        &quot;$ref&quot;: f&quot;#/components/messages/{handler.response_schema.__name__}&quot;<br>                    }<br><br>        return spec</pre><p>At doc time, scan all registered handlers and build an AsyncAPI spec:</p><p>Then convert to YAML or JSON as needed.</p><h3>4) Django views for HTML / JSON / YAML</h3><pre>from django.http import HttpResponse<br>from django.template.loader import render_to_string<br>import json<br><br><br>def asyncapi_html(request):<br>    spec = AsyncAPIGenerator.generate_spec(<br>        title=&quot;WebSocket API&quot;,<br>        version=&quot;1.0.0&quot;,<br>        description=&quot;Realtime API&quot;,<br>        server_url=request.build_absolute_uri(&quot;/ws&quot;),<br>    )<br>    html = render_to_string(&quot;websocket/asyncapi.html&quot;, {&quot;spec_json&quot;: json.dumps(spec), &quot;title&quot;: spec[&quot;info&quot;][&quot;title&quot;]})<br>    return HttpResponse(html)<br><br><br>def asyncapi_json(request):<br>    spec = AsyncAPIGenerator.generate_spec(...)<br>    return HttpResponse(json.dumps(spec, indent=2), content_type=&quot;application/json&quot;)</pre><p>Expose three endpoints:</p><h3>5) Render a Swagger-like UI</h3><pre>&lt;link rel=&quot;stylesheet&quot; href=&quot;https://unpkg.com/@asyncapi/react-component@latest/styles/default.min.css&quot;&gt;<br>&lt;script src=&quot;https://unpkg.com/@asyncapi/react-component@latest/browser/standalone/index.js&quot;&gt;&lt;/script&gt;<br><br>&lt;div id=&quot;asyncapi&quot;&gt;&lt;/div&gt;<br>&lt;script&gt;<br>  AsyncApiStandalone.render({<br>    schema: {{ spec_json|safe }},<br>    config: { show: { sidebar: true } }<br>  }, document.getElementById(&#39;asyncapi&#39;));<br>&lt;/script&gt;</pre><p>Use the official AsyncAPI React component to render docs in HTML:</p><p>This gives you a fully interactive UI with channels, messages, and schemas.</p><h3>Practical tips</h3><ul><li><strong>Cache the spec</strong> in production (15 min is plenty)</li><li><strong>Add tags</strong> in the decorator to group operations</li><li><strong>Use examples</strong> in Pydantic models to improve docs</li><li><strong>Keep message names stable</strong> (clients will depend on them)</li></ul><h3>Why this automation works</h3><p>AsyncAPI is the WebSocket equivalent of Swagger. The missing piece is <strong>automated generation from code</strong>. With a registry + schemas, the docs stay accurate with almost zero manual maintenance.</p><h3>Final takeaway</h3><p>If you already use Django for WebSockets, this is the minimum viable way to get <strong>Swagger-grade AsyncAPI docs</strong> without hand-editing YAML. Once the registry is in place, your docs stay in sync as the code evolves automatically.</p><h3>Next steps</h3><ul><li>Add auth requirements per channel</li><li>Expose both AsyncAPI 2.6 and 3.0</li><li>Generate specs as part of CI to detect breaking changes</li></ul><p>If you already use Django for WebSockets, this is the simplest path to Swagger-grade docs.</p><p><em>Originally published at </em><a href="https://pandabb3356.github.io/django-automated-asyncapi-docs.html"><em>https://pandabb3356.github.io</em></a><em> on December 22, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21d5df74a8a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching Systems (Part 3): Building Cache-Aside in Go with Redis]]></title>
            <link>https://medium.com/@joloiuy/caching-systems-part-3-building-cache-aside-in-go-with-redis-27e40dd7ef89?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/27e40dd7ef89</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 08:54:31 GMT</pubDate>
            <atom:updated>2025-12-25T13:56:40.085Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UqUjB6H9Db17H9-r" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@nateggrant?utm_source=local&amp;utm_medium=referral"><em>Nate Grant</em></a><em> on </em><a href="https://unsplash.com/photos/dFF8z3WH5FI?utm_source=local&amp;utm_medium=referral"><em>Unsplash</em></a></figcaption></figure><p>Part 2 covered invalidation strategies. This part shows a <strong>cache-aside implementation in Go</strong> that is safe in production: TTL jitter, request coalescing, and defensive fallbacks.</p><h3>Design goals</h3><ul><li>Cache reads are fast and non-fatal</li><li>Cache misses do not stampede the DB</li><li>Writes invalidate or refresh cache deterministically</li></ul><p><strong>Assumptions</strong> — Redis as shared cache — JSON serialization — go-redis client</p><h3>Cache key strategy</h3><p>Keep it boring and deterministic:</p><pre>user:{id}</pre><p>If you later adopt versioned caches, make it:</p><pre>user:{id}:v{version}</pre><h3>Go implementation (cache-aside + singleflight)</h3><pre>package cache<br><br>import (<br>    &quot;context&quot;<br>    &quot;encoding/json&quot;<br>    &quot;math/rand&quot;<br>    &quot;time&quot;<br><br>    &quot;golang.org/x/sync/singleflight&quot;<br>    &quot;github.com/redis/go-redis/v9&quot;<br>)<br><br>type User struct {<br>    ID    string `json:&quot;id&quot;`<br>    Name  string `json:&quot;name&quot;`<br>    Email string `json:&quot;email&quot;`<br>}<br><br>type Store struct {<br>    rdb   *redis.Client<br>    group singleflight.Group<br>}<br><br>func NewStore(rdb *redis.Client) *Store {<br>    return &amp;Store{rdb: rdb}<br>}<br><br>func (s *Store) cacheKey(id string) string {<br>    return &quot;user:&quot; + id<br>}<br><br>func ttlWithJitter(base time.Duration) time.Duration {<br>    // Add up to 10% jitter to spread expirations<br>    jitter := time.Duration(rand.Int63n(int64(base / 10)))<br>    return base + jitter<br>}<br><br>func (s *Store) GetUser(ctx context.Context, id string, dbFetch func(context.Context, string) (*User, error)) (*User, error) {<br>    key := s.cacheKey(id)<br><br>    // 1) Try cache<br>    if b, err := s.rdb.Get(ctx, key).Bytes(); err == nil {<br>        var u User<br>        if jsonErr := json.Unmarshal(b, &amp;u); jsonErr == nil {<br>            return &amp;u, nil<br>        }<br>    }<br><br>    // 2) Singleflight to avoid stampede<br>    v, err, _ := s.group.Do(key, func() (any, error) {<br>        u, err := dbFetch(ctx, id)<br>        if err != nil {<br>            return nil, err<br>        }<br>        if u == nil {<br>            return nil, nil<br>        }<br>        if b, err := json.Marshal(u); err == nil {<br>            _ = s.rdb.Set(ctx, key, b, ttlWithJitter(10*time.Minute)).Err()<br>        }<br>        return u, nil<br>    })<br>    if err != nil {<br>        return nil, err<br>    }<br>    if v == nil {<br>        return nil, nil<br>    }<br>    return v.(*User), nil<br>}<br><br>func (s *Store) InvalidateUser(ctx context.Context, id string) error {<br>    return s.rdb.Del(ctx, s.cacheKey(id)).Err()<br>}</pre><h3>Write path: update DB, then invalidate</h3><p><strong>Golden rule:</strong> DB is source of truth. Cache follows.</p><pre>func (s *Store) UpdateUser(ctx context.Context, id string, dbUpdate func(context.Context, string) error) error {<br>    if err := dbUpdate(ctx, id); err != nil {<br>        return err<br>    }<br>    return s.InvalidateUser(ctx, id)<br>}</pre><p>If you need read-your-writes consistency, consider: — Versioned keys (Part 2) — Updating cache immediately after write</p><h3>Production notes</h3><ul><li><strong>Negative caching:</strong> cache “not found” for a short TTL to reduce DB hits</li><li><strong>Timeouts:</strong> enforce short Redis timeouts; cache failures should not take down reads</li><li><strong>Metrics:</strong> track hit rate, miss rate, and stampede events</li><li><strong>Backoff:</strong> if Redis is unhealthy, bypass cache temporarily</li></ul><h3>Final takeaway</h3><p>Cache-aside is simple, but production-safe cache-aside is deliberate. Add jitter, coalescing, and clear invalidation and you get the best of both worlds: speed without hidden correctness debt.</p><p><em>Originally published at </em><a href="https://pandabb3356.github.io/caching-systems-part-3-go-cache-aside-redis.html"><em>https://pandabb3356.github.io</em></a><em> on December 21, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27e40dd7ef89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching Systems (Part 2): Versioned Caches, Pub/Sub Invalidation, and Consistency]]></title>
            <link>https://medium.com/@joloiuy/caching-systems-part-2-versioned-caches-pub-sub-invalidation-and-consistency-7904f43469ac?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7904f43469ac</guid>
            <category><![CDATA[pub-sub]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[consistency]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 08:54:21 GMT</pubDate>
            <atom:updated>2025-12-24T14:52:27.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uKoyvYzXAoUBYDU5" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@robertbye?utm_source=local&amp;utm_medium=referral"><em>Robert Bye</em></a><em> on </em><a href="https://unsplash.com/photos/j60Nt3ZvtFI?utm_source=local&amp;utm_medium=referral"><em>Unsplash</em></a></figcaption></figure><p>Part 1 explained caching layers and failure modes. This part is about <strong>keeping caches correct</strong> when data changes in a distributed system: versioned keys, event-driven invalidation, and the consistency trade-offs you actually live with.</p><h3>1) Versioned caches: invalidate by changing the key</h3><p>Instead of deleting keys, you <strong>bump a version</strong> and let old keys expire naturally.</p><p><strong>Key pattern:</strong></p><p><strong>How it works:</strong> — Store the current version in DB or a small metadata store. — Reads fetch the version, then read the versioned cache key. — Writes increment the version.</p><p><strong>Pros</strong> — Invalidation is cheap and reliable (no delete storms). — Old keys can expire with TTL in the background. — Works across many caches and services.</p><p><strong>Cons</strong> — Extra read (to get version) or version is cached too. — Requires a version store with strong write semantics.</p><p><strong>Where it shines</strong> — User profiles, product pages, or any entity with frequent updates. — Multi-service systems where you cannot fan-out invalidations reliably.</p><h3>2) Pub/Sub invalidation: push change events</h3><p>In this model, writes <strong>publish an event</strong>. Consumers invalidate or update their caches.</p><p><strong>Event payload (example):</strong></p><pre>{ &quot;entity&quot;: &quot;user&quot;, &quot;id&quot;: &quot;123&quot;, &quot;action&quot;: &quot;updated&quot;, &quot;ts&quot;: 1734790000 }</pre><p><strong>Typical flow</strong> 1) Write to DB 2) Publish event 3) Cache owners receive event 4) Invalidate or update cache</p><p><strong>Why it fails if you do it naively</strong> — Events can be dropped, delayed, or reordered. — Consumers can be down when events publish.</p><p><strong>How to make it reliable</strong> — Use an <strong>outbox pattern</strong> (store events in DB, publish asynchronously). — Make handlers idempotent. — Use a durable stream (Kafka/NATS) instead of volatile pubsub when correctness matters.</p><h3>3) TTL is not enough; use soft TTL and stale-while-revalidate</h3><p>TTL alone creates stampedes and synchronized expirations.</p><p><strong>Better pattern</strong> — <strong>Soft TTL:</strong> consider cache stale before it truly expires. — Serve stale data briefly while one request refreshes in background. — Add jitter to TTL to avoid thundering herds.</p><p><strong>Example strategy</strong> — Hard TTL: 10 minutes — Soft TTL: 8 minutes — If age &gt; 8 minutes, refresh asynchronously</p><h3>4) Stampede control: avoid N concurrent recomputations</h3><p>When popular keys expire, you can melt the DB.</p><p><strong>Mitigations</strong> — Singleflight (request coalescing) — Locking on recompute — Probabilistic early refresh — Pre-warming hot keys</p><h3>5) Consistency is a choice, not a bug</h3><p>There is no perfect cache consistency, only <strong>explicit trade-offs</strong>.</p><p><strong>Common models</strong> — <strong>Eventual consistency:</strong> cheap, fast, some staleness — <strong>Bounded staleness:</strong> TTL-based, measurable drift — <strong>Read-your-writes:</strong> require versioning or session caches — <strong>Strong consistency:</strong> usually too expensive to maintain for caches</p><p><strong>Rule of thumb</strong> — If a bug is catastrophic, skip caching for that path. — If staleness is acceptable, make it measurable and visible.</p><h3>6) A practical decision matrix</h3><p>Use this to pick a strategy per domain:</p><ul><li><strong>User profile:</strong> versioned keys + TTL + background refresh</li><li><strong>Search results:</strong> TTL + soft TTL + async refresh</li><li><strong>Feature flags:</strong> pub/sub with durable stream + short TTL</li><li><strong>Financial balances:</strong> avoid cache or use read-your-writes session cache only</li></ul><h3>Final takeaway</h3><p>Correctness in caches is <strong>not automatic</strong>. It requires: — deterministic invalidation (versioning), — durable change propagation (pub/sub + outbox), — and explicit consistency guarantees.</p><p>Part 3 shows how to build a cache-aside layer in Go with these patterns baked in.</p><p><em>Originally published at </em><a href="https://pandabb3356.github.io/caching-systems-part-2-versioned-caches-pubsub-consistency.html"><em>https://pandabb3356.github.io</em></a><em> on December 21, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7904f43469ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching Systems (Part 1): Layers, Strategies, and Failure Modes]]></title>
            <link>https://medium.com/@joloiuy/caching-systems-part-1-layers-strategies-and-failure-modes-e6b771332873?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6b771332873</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[reliability]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[caching-strategies]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 08:27:16 GMT</pubDate>
            <atom:updated>2025-12-23T14:46:50.888Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BSxhFLRTeH0HVpbP" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@sqrlsm?utm_source=local&amp;utm_medium=referral"><em>Tarn Nguyen</em></a><em> on </em><a href="https://unsplash.com/photos/_Ur3RjaRSDs?utm_source=local&amp;utm_medium=referral"><em>Unsplash</em></a></figcaption></figure><p>Caching is one of the highest-leverage tools in backend engineering: it can turn expensive work into cheap work, flatten latency spikes, and reduce infrastructure cost. It can also quietly introduce correctness bugs, inconsistent user experiences, and operational incidents.</p><p>This article is not a “use Redis” tutorial. It is a practical deep dive into how caching works <strong>as a system</strong> -across layers, time, and failure modes-so you can design caches you can actually trust.</p><h3>What Caching Really Is</h3><p>A cache is a <strong>time-bounded copy</strong> of data or computation that trades one resource for another:</p><p>Every cache makes an implicit promise:</p><blockquote><em>“This value is probably good enough until time </em>T<em> or until event </em>E<em>.”</em></blockquote><p>You are not just choosing a technology. You are choosing <strong>a consistency model</strong>.</p><h3>The Caching Stack: Where Caches Live</h3><p>Most production systems have multiple caches stacked on top of each other. Understanding them as a pipeline helps you reason about behavior.</p><p>Think of caching as <strong>progressively closer copies</strong> of data and computation.</p><h3>1) Request-scope cache (per-request)</h3><p>This cache lives only for the lifetime of a single request.</p><p>Examples:</p><ul><li>Memoization inside a request handler</li><li>Django cached_property</li><li>ORM identity maps</li><li>GraphQL DataLoader-style batching</li></ul><p>Why it matters:</p><ul><li>Eliminates duplicate work inside one request</li><li>Collapses N+1 query patterns</li></ul><p>Properties:</p><h3>2) In-process server cache</h3><p>Cached in application memory.</p><p>Examples:</p><p>Pros:</p><ul><li>Extremely fast (no network)</li><li>Simple mental model</li></ul><p>Cons:</p><ul><li>Not shared across instances</li><li>Evicted on deploy or restart</li></ul><p>Best used for:</p><h3>3) Shared server-side cache (Redis / Memcached)</h3><p>This is the classic backend cache layer.</p><p>Characteristics:</p><p>Common responsibilities:</p><p>Design requirement:</p><h3>4) Reverse proxy cache</h3><p>Sits in front of application servers.</p><p>Effective when:</p><p>Trade-offs:</p><ul><li>Limited visibility into per-user context</li><li>Invalidation can be coarse-grained</li></ul><h3>5) Database-internal caches</h3><p>Always present, often forgotten.</p><p>Includes:</p><p>Important implication:</p><blockquote><em>You may already benefit from caching even without Redis.</em></blockquote><p>In many cases, fixing queries outperforms adding a new cache layer.</p><p><strong>Key idea:</strong> you cannot reason about caching by looking at Redis alone. Your system already caches in multiple places.</p><h3>What Should Be Cached?</h3><p>A useful way to decide is to categorize what you want to cache:</p><h3>A) Content caching (responses)</h3><p>Cache the full HTTP response.</p><h3>B) Data caching (objects, query results)</h3><p>Cache the underlying data representation.</p><h3>C) Computation caching (derived results)</h3><p>Cache expensive computations.</p><ul><li>Ranking, aggregation, recommendations, reports</li><li>Often benefits most from “stale-while-revalidate” patterns</li></ul><h3>D) Negative caching</h3><p>Cache “nothing here.”</p><h3>TTL Is Not Invalidation</h3><p>TTL (time-to-live) is the most common caching tool because it’s easy:</p><ul><li>Put value in cache for 60 seconds</li><li>Recompute after it expires</li></ul><p>But TTL is <strong>not invalidation</strong>. It is a bounded staleness guarantee.</p><p>Use TTL when:</p><ul><li>Data changes frequently, and you can tolerate being “a bit behind”</li><li>Exact freshness is not critical (feeds, counts, trending lists)</li></ul><p>Avoid TTL-only caches when:</p><ul><li>Users expect strong correctness (billing, permissions, inventory)</li><li>A single stale value can cause harm</li></ul><h3>Invalidation Strategies That Scale</h3><p>The “two hard things” joke exists for a reason: invalidation is where systems fail.</p><h3>1) Write-through</h3><p>Update cache at the same time you write to the source of truth.</p><ul><li>Pros: reads are fast and fresh</li><li>Cons: writes become slower, and failures are tricky (what if cache update fails?)</li></ul><h3>2) Write-back (rare)</h3><p>Write to cache first, flush to DB later.</p><ul><li>Pros: extremely fast writes</li><li>Cons: complexity and data-loss risk; usually not worth it outside specialized systems</li></ul><h3>3) Cache-aside (lazy loading)</h3><p>On read: check cache; if missing, load from DB and store. On write: update DB, then invalidate cache.</p><ul><li>Pros: simple and popular</li><li>Cons: invalidation is your job; race conditions exist</li></ul><h3>4) Event-driven invalidation</h3><p>Publish events on writes; consumers invalidate relevant keys.</p><ul><li>Pros: good decoupling and scale</li><li>Cons: requires a reliable event pipeline and careful key design</li></ul><h3>Correctness Pitfalls and How to Avoid Them</h3><h3>Cache key design errors</h3><p>Bad cache keys cause incorrect data to leak across users.</p><p>Rules of thumb:</p><ul><li>Include all dimensions that affect the result (user id, locale, permissions, feature flags)</li><li>Normalize inputs (lowercase, stable sorting, canonical query params)</li><li>Version your keys (v1: prefix) so you can invalidate by migration</li></ul><p>Example key shape:</p><h3>The thundering herd (cache stampede)</h3><p>When a hot key expires, many requests recompute at once.</p><p>Mitigations:</p><ul><li><strong>Probabilistic early refresh</strong>: refresh before TTL hits zero</li><li><strong>Soft TTL + hard TTL</strong>: serve stale value briefly while refreshing in background</li><li><strong>Single-flight locking</strong>: only one worker recomputes; others wait or serve stale</li></ul><h3>Caching errors and timeouts</h3><p>Caching failures should degrade gracefully.</p><ul><li>If cache is down, your app must still work (maybe slower)</li><li>Treat the cache as an optimization, not a dependency-unless you’ve designed it to be one</li></ul><h3>Caching authorization and permissions</h3><p>A classic incident pattern:</p><ol><li>Cache a response for user A</li><li>Serve it to user B by accident</li></ol><p>If your response depends on auth context, <strong>never share keys</strong> across users unless you have a robust permission-aware key strategy.</p><h3>Stale-While-Revalidate: The Most Practical “Advanced” Pattern</h3><p>Many teams aim for perfect freshness and end up with brittle systems. A better pattern for many endpoints is:</p><ul><li>Serve cached value immediately (even if slightly stale)</li><li>Refresh asynchronously when it approaches expiration</li></ul><p>This pattern smooths load spikes and improves tail latency.</p><p>A simple mental model:</p><ul><li><strong>Hard TTL</strong>: maximum staleness you will ever serve</li><li><strong>Soft TTL</strong>: when you start refreshing</li></ul><p>When soft TTL is hit:</p><ul><li>If cache has value: serve it</li><li>Trigger a background refresh</li></ul><p>When hard TTL is hit:</p><p>This turns cache expiry from a cliff into a ramp.</p><h3>Observability: If You Can’t Measure It, You Can’t Trust It</h3><p>You should be able to answer these questions from dashboards:</p><ul><li>Cache hit ratio (overall and per key group)</li><li>Miss latency and backend load during misses</li><li>Evictions (memory pressure or policy)</li><li>Hot keys (top N keys by QPS)</li><li>Stampede symptoms (miss spikes, lock contention)</li></ul><p>Be cautious with “hit ratio” as a vanity metric: a high hit ratio can still hide correctness bugs or stampedes.</p><h3>When Not to Cache</h3><p>Caching is not free. Don’t cache when:</p><ul><li>Data is highly personalized and low-reuse</li><li>Results must be correct in real time (payments, stock levels, permissions)</li><li>You can achieve the performance goal by optimizing queries, indexes, or batching</li><li>The operational complexity outweighs the savings</li></ul><p>A good heuristic:</p><blockquote><em>Cache after you understand the bottleneck, not before.</em></blockquote><h3>A Practical Checklist</h3><p>Before adding a cache, confirm:</p><ul><li><strong>What are you caching?</strong> response / data / computation / negative</li><li><strong>What is the acceptable staleness?</strong> seconds? minutes? must be exact?</li><li><strong>What triggers invalidation?</strong> TTL only? writes? events?</li><li><strong>What is the key shape?</strong> versioned, canonical, permission-aware</li><li><strong>How do you prevent stampedes?</strong> soft/hard TTL, single-flight, jitter</li><li><strong>What happens when cache fails?</strong> fallback path and timeouts</li><li><strong>How will you measure success?</strong> p95 latency, DB QPS, error rate</li></ul><h3>Final Takeaway</h3><p>Caching is not about making things fast. It is about <strong>deciding where you are willing to be stale, and for how long</strong>.</p><p>A concrete conclusion you can apply:</p><ul><li>Start with <strong>request-scope caching</strong> to eliminate duplicate work safely.</li><li>Add <strong>shared caches (Redis/CDN)</strong> only after you understand reuse patterns.</li><li>Use <strong>TTL for tolerance</strong>, not correctness.</li><li>Treat <strong>invalidation as a design requirement</strong>, not an afterthought.</li><li>Prefer <strong>stale-while-revalidate</strong> over hard expiration for user-facing reads.</li><li>Design cache keys and observability before you ship the cache.</li></ul><p>If you cannot clearly answer <em>what can be stale, for how long, and what breaks if it is</em>, you are not ready to add a cache.</p><p>Caching works best when it is deliberate, bounded, and measurable-not when it is added reactively in response to slow queries.</p><p><em>Originally published at </em><a href="https://pandabb3356.github.io/caching-systems-part-1-layers-strategies-failure-modes.html"><em>https://pandabb3356.github.io</em></a><em> on December 21, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6b771332873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django DRF-Spectacular Envelope Responses: Advanced Patterns and Trade-offs]]></title>
            <link>https://medium.com/@joloiuy/django-drf-spectacular-envelope-responses-advanced-patterns-and-trade-offs-ef228e6e2562?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef228e6e2562</guid>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[swagger]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 06:00:04 GMT</pubDate>
            <atom:updated>2025-12-22T08:12:20.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xMcNDRfiCaJz4Wla" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@robertbye?utm_source=local&amp;utm_medium=referral"><em>Robert Bye</em></a><em> on </em><a href="https://unsplash.com/photos/Eq76mDacpto?utm_source=local&amp;utm_medium=referral"><em>Unsplash</em></a></figcaption></figure><blockquote><em>This article is a continuation of </em><strong><em>“Django DRF-Spectacular: Documenting Custom Envelope Responses”</em></strong><em>. If you have not read the previous piece, start there for the fundamentals.</em></blockquote><p>Once you understand <em>how</em> to document envelope responses, the next challenge is deciding <strong>how far to push the abstraction</strong>. In larger systems, naive envelope patterns often collide with schema accuracy, long-term maintainability, and developer ergonomics.</p><p>This article explores <strong>advanced patterns, edge cases, and trade-offs</strong> when using drf-spectacular with custom envelope responses.</p><h3>What Is Actually “Advanced” Here?</h3><p>This article is <em>not</em> advanced because of complex code. It is advanced because it focuses on <strong>system-level consequences</strong> rather than mechanics.</p><p>Specifically, the advanced aspects are:</p><ul><li><strong>Schema truth vs runtime convenience</strong> — analyzing how global envelopes distort OpenAPI contracts</li><li><strong>Error modeling as a separate domain</strong> — rejecting the idea that success and error responses should share the same shape</li><li><strong>Pagination as a first-class schema concern</strong> — preserving list semantics instead of flattening them into data: []</li><li><strong>Explicit rejection of generics</strong> — explaining why Python typing abstractions fail under DRF schema introspection</li><li><strong>Decision-oriented guidance</strong> — a matrix that helps teams choose patterns based on API context, not preference</li></ul><p>If you are only looking for <em>“how to make drf-spectacular show my envelope”</em>, the previous article is enough.</p><p>This piece is about <strong>why certain envelope designs stop scaling</strong> -organizationally and technically.</p><h3>The Hidden Cost of a Global Envelope</h3><p>A common approach is to enforce a response envelope globally by overriding APIView.finalize_response:</p><p>While this guarantees runtime consistency, it creates a <strong>schema visibility gap</strong>:</p><ul><li>drf-spectacular never sees the final response shape</li><li>status-specific responses (400 / 401 / 404) become ambiguous</li><li>pagination and list responses lose type information</li></ul><p>At scale, this pattern forces developers to manually patch schemas everywhere, negating the benefits of automation.</p><p><strong>Rule of thumb:</strong> global envelopes optimize runtime symmetry at the expense of documentation truth.</p><h3>Pattern 1: Schema-First Envelope Design</h3><p>Instead of wrapping responses at runtime, define the envelope <strong>at the schema layer first</strong>.</p><p>Then bind the envelope explicitly per endpoint using typed serializers.</p><p>This approach treats OpenAPI as a <strong>contract</strong>, not a side effect.</p><h3>Why this scales better</h3><ul><li>Every response is intentional</li><li>Schema diffs become meaningful in code reviews</li><li>Frontend contracts remain stable</li></ul><h3>Pattern 2: Error Envelopes Are Not Success Envelopes</h3><p>One of the most common mistakes is reusing the same envelope for errors.</p><p>This hides critical semantics:</p><ul><li>HTTP status codes already convey failure</li><li>error payloads are structurally different</li><li>clients cannot reliably branch on data</li></ul><p>A better approach is <strong>separate schemas</strong>:</p><p>Then document them explicitly:</p><p>This preserves semantic clarity and accurate client generation.</p><h3>Pattern 3: Pagination and List Responses</h3><p>Pagination is where envelope abstractions often break.</p><p>A naive envelope loses the list shape:</p><p>Instead, treat pagination as a <strong>first-class data structure</strong>:</p><p>This preserves:</p><ul><li>list semantics</li><li>pagination metadata</li><li>OpenAPI client correctness</li></ul><h3>Pattern 4: Generics and Why Python Cannot Save You</h3><p>It is tempting to want a generic envelope:</p><p>Python’s typing system does not survive runtime introspection in DRF serializers. drf-spectacular cannot resolve generics without explicit serializers.</p><p><strong>Reality check:</strong></p><ul><li>Generics help humans</li><li>Concrete serializers help schemas</li></ul><p>In practice, explicit duplication wins.</p><h3>Pattern 5: Inline Overrides as an Escape Hatch</h3><p>Inline schemas are acceptable when:</p><ul><li>the endpoint is unstable</li><li>the payload is trivial</li><li>the API is internal-only</li></ul><p>But overuse creates invisible contracts.</p><p>If a schema matters, give it a name.</p><h3>Decision Matrix</h3><pre>Scenario           -&gt; Recommended Pattern<br>Public API         -&gt; Typed envelope serializers<br>Internal tools     -&gt; Inline overrides<br>Pagination         -&gt; Dedicated paginated envelope<br>Errors             -&gt; Separate error envelope<br>Global envelope    -&gt; Avoid for schema accuracy</pre><h3>Final Takeaway</h3><p>Envelope responses are not a stylistic preference. They are a <strong>design commitment</strong>.</p><p>The moment your API becomes a contract-consumed by frontend teams, client SDKs, or external users-envelope abstractions stop being a runtime convenience and start demanding <strong>explicit schema ownership</strong>.</p><p>If you choose to centralize response behavior, you must pay for it in documentation clarity. If you are unwilling to model success, error, and pagination as distinct schema concerns, a global envelope will eventually work against you.</p><p>The real lesson is simple:</p><blockquote><strong><em>Envelope design is no longer a technical choice once your API has consumers.</em></strong></blockquote><p>Treat OpenAPI as a first-class design surface, not a side effect of implementation, and your envelope patterns will scale-for both systems and teams.</p><p><em>Originally published at </em><a href="https://pandabb3356.github.io/django-drf-spectacular-envelope-responses-advanced.html"><em>https://pandabb3356.github.io</em></a><em> on December 21, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef228e6e2562" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django DRF-Spectacular: Documenting Custom Envelope Responses]]></title>
            <link>https://medium.com/@joloiuy/django-drf-spectacular-documenting-custom-envelope-responses-7dfd5d229f35?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dfd5d229f35</guid>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Sun, 21 Dec 2025 03:48:36 GMT</pubDate>
            <atom:updated>2025-12-21T05:22:41.848Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rgE17fL_ajwHlSrK.jpg" /><figcaption><em>Photo by </em><a href="https://unsplash.com/@ryuldavidson?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Ryul Davidson</em></a><em> on </em><a href="https://unsplash.com/photos/PcyrQsX5f4w?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText"><em>Unsplash</em></a></figcaption></figure><p>Many teams using Django REST Framework (DRF) adopt a <strong>custom response envelope</strong> to keep API responses consistent across services. A common pattern looks like this:</p><pre>{<br>  &quot;success&quot;: true,<br>  &quot;message&quot;: &quot;OK&quot;,<br>  &quot;data&quot;: {<br>    &quot;id&quot;: 1,<br>    &quot;name&quot;: &quot;Alice&quot;<br>  }<br>}</pre><p>While this structure is convenient for frontend applications, it often causes confusion when generating OpenAPI documentation with <strong>drf-spectacular</strong>. By default, drf-spectacular assumes that your serializer represents the <em>entire</em> response body, which is not true when you wrap data inside a custom envelope.</p><p>This article explains why this mismatch happens and shows clean, maintainable ways to document custom envelope responses correctly.</p><h3>Why drf-spectacular Gets It Wrong by Default</h3><p>In DRF, serializers usually describe the exact JSON returned by the API. When you return a wrapped response manually — such as {&quot;success&quot;: true, &quot;data&quot;: serializer.data}—the schema generator has no way to infer that extra structure.</p><p>As a result, the generated OpenAPI schema typically documents only the inner serializer, misleading API consumers and frontend developers.</p><h3>Option 1: Create an Explicit Envelope Serializer (Recommended)</h3><p>The most explicit and maintainable solution is to define a reusable <strong>envelope serializer</strong>.</p><pre>from rest_framework import serializers<br><br>class EnvelopeSerializer(serializers.Serializer):<br>    success = serializers.BooleanField()<br>    message = serializers.CharField(required=False)<br>    data = serializers.JSONField()</pre><p>Then, use extend_schema to document the response:</p><pre>from drf_spectacular.utils import extend_schema<br><br>@extend_schema(<br>    responses=EnvelopeSerializer<br>)<br>def get(self, request):<br>    ...</pre><h3>Pros</h3><ul><li>Clear and explicit schema</li><li>Reusable across endpoints</li><li>Works perfectly with schema generation</li></ul><h3>Cons</h3><ul><li>data is loosely typed unless customized further</li></ul><h3>Option 2: Typed Envelope with Generic Pattern</h3><p>For better typing, you can define multiple envelope serializers for different payloads:</p><pre>class UserDataSerializer(serializers.Serializer):<br>    id = serializers.IntegerField()<br>    name = serializers.CharField()<br><br><br>class UserEnvelopeSerializer(serializers.Serializer):<br>    success = serializers.BooleanField()<br>    message = serializers.CharField(required=False)<br>    data = UserDataSerializer()</pre><p>This produces fully accurate OpenAPI documentation at the cost of some duplication.</p><h3>Option 3: Inline Schema Override</h3><p>For simple or one-off endpoints, you can define the envelope inline:</p><pre>from drf_spectacular.utils import extend_schema<br>from drf_spectacular.types import OpenApiTypes<br><br>@extend_schema(<br>    responses={<br>        200: {<br>            &quot;type&quot;: &quot;object&quot;,<br>            &quot;properties&quot;: {<br>                &quot;success&quot;: {&quot;type&quot;: &quot;boolean&quot;},<br>                &quot;message&quot;: {&quot;type&quot;: &quot;string&quot;},<br>                &quot;data&quot;: {&quot;type&quot;: &quot;object&quot;},<br>            }<br>        }<br>    }<br>)<br>def get(self, request):<br>    ...</pre><h3>When to use this</h3><ul><li>Prototyping</li><li>Simple endpoints</li><li>Minimal reuse expected</li></ul><h3>Should You Use a Global Envelope?</h3><p>Some teams try to enforce a global envelope by overriding APIView.finalize_response. While this works at runtime, it complicates schema generation and often results in inaccurate OpenAPI docs.</p><p>If you choose this approach, <strong>explicit schema definitions are mandatory</strong> — automatic inference will not work.</p><h3>Best Practices Summary</h3><ul><li>Prefer explicit envelope serializers</li><li>Keep schema definitions close to the view</li><li>Avoid magic global overrides for documentation</li><li>Treat OpenAPI as a first-class contract, not a side effect</li></ul><h3>Final Thoughts</h3><p>drf-spectacular is powerful, but it cannot guess response shapes that serializers do not describe. Once you accept that limitation, documenting custom envelope responses becomes straightforward and predictable.</p><p>Clear schemas lead to happier frontend developers, fewer integration bugs, and APIs that scale gracefully.</p><p><em>Originally published at </em><a href="https://pandabb3356.github.io/django-drf-spectacular-custom-envelope-responses.html"><em>https://pandabb3356.github.io</em></a><em> on December 21, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dfd5d229f35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Database Documentation with tbls, Drone CI + MkDocs, and Cloudflare Pages]]></title>
            <link>https://medium.com/@joloiuy/streamlining-database-documentation-with-tbls-drone-ci-mkdocs-and-cloudflare-pages-8f46fd8b80f6?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f46fd8b80f6</guid>
            <category><![CDATA[drone-ci]]></category>
            <category><![CDATA[database-schema]]></category>
            <category><![CDATA[mkdocs]]></category>
            <category><![CDATA[cloudflare-pages]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Mon, 10 Jun 2024 06:52:06 GMT</pubDate>
            <atom:updated>2024-06-10T06:52:06.564Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajmkdytoG0zba6Vk-EtMfA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Brett Jordan</a> on <a href="https://unsplash.com/photos/a-scrabbled-wooden-cross-with-the-word-plan-spelled-on-it-gL-wABq7LUU?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>Maintaining up-to-date database schema documentation is a critical yet challenging task in software development. To automate and simplify this process, we can leverage a powerful combination of tools: <strong><em>tbls</em></strong> for generating database schema documentation, <strong><em>Drone CI</em></strong> for continuous integration, <strong><em>MkDocs</em></strong> for generating static site documentation, and <strong><em>Cloudflare Pages</em></strong> for hosting. This guide will walk you through setting up an automated pipeline that keeps your database schema documentation current and easily accessible.</p><blockquote>Note: This setup is an experiment to demonstrate how these tools can work together seamlessly.</blockquote><h3>Prerequisites</h3><p>Before we dive into the setup, ensure you have the following:</p><ol><li>Make a docker image for migration.</li><li>A Drone CI server set up.</li><li>A Cloudflare account for deploying pages.</li></ol><h4>Step 1: Install and Configure tbls</h4><p>tbls is a tool for generating database schema documentation in various formats. Install it using Go:</p><pre>go install github.com/k1LoW/tbls@latest</pre><p>Configure tbls by creating a tbls.yml file:</p><pre>dsn: &quot;your_database_dsn&quot;  # Replace with your database DSN<br>docPath: &quot;docs&quot;  # Output directory for the documentation</pre><p>Run tbls to generate the documentation:</p><pre>tbls doc -c tbls.yml --rm-dist</pre><p>This will create the initial documentation in the docs directory.</p><h4>Step 2: Set Up MkDocs</h4><p>MkDocs is a static site generator that’s geared towards project documentation. We will use the popular mkdocs-material theme to make our documentation visually appealing. Install MkDocs and the Material theme:</p><pre>pip install mkdocs mkdocs-material</pre><p>Create a new MkDocs project:</p><pre>mkdocs new .</pre><p>Configure MkDocs by editing the mkdocs.yml file:</p><pre>site_name: &quot;Database Schema Documentation&quot;<br>docs_dir: &quot;docs&quot;<br>theme:<br>  name: &quot;material&quot;<br># other settings ...</pre><h4>Step 3: Configure Drone CI Pipelines (Using Starlark)</h4><p>Drone CI is a powerful continuous integration tool. We will create two separate pipelines: one for generating the database schema markdown files and another for building and deploying the MkDocs site using Cloudflare Pages.</p><p>Create a .drone.star file in your repository with the following content:</p><pre>def generate_docs_pipeline():<br>    return {<br>        &quot;kind&quot;: &quot;pipeline&quot;,<br>        &quot;type&quot;: &quot;{your_pipeline_type}&quot;,  # docker, kubernetes ...<br>        &quot;name&quot;: &quot;generate-docs&quot;,<br>        <br>        &quot;steps&quot;: [<br>            {<br>               &quot;name&quot;: &quot;{your_name}&quot;,<br>               &quot;image&quot;: &quot;{your_image}&quot;,<br>               &quot;commands&quot;: [<br>                  &quot;{your_migrate_command}&quot;<br>               ],<br>            },<br>            {<br>                &quot;name&quot;: &quot;generate-docs&quot;,<br>                &quot;image&quot;: &quot;golang:1.18&quot;,<br>                &quot;commands&quot;: [<br>                    &quot;go install github.com/k1LoW/tbls@latest&quot;,<br>                    &quot;tbls doc&quot;<br>                ],<br>            }<br>        ],<br>        <br>        &quot;services&quot;: [<br>            {<br>                &quot;name&quot;: &quot;database&quot;,<br>                &quot;image&quot;: &quot;postgres:13&quot;,<br>                &quot;environment&quot;: {<br>                    &quot;POSTGRES_DB&quot;: &quot;your_db_name&quot;,<br>                    &quot;POSTGRES_USER&quot;: &quot;your_db_user&quot;,<br>                    &quot;POSTGRES_PASSWORD&quot;: &quot;your_db_password&quot;<br>                },<br>            }<br>        ],<br>        <br>        &quot;trigger&quot;: {<br>            &quot;branch&quot;: [<br>                &quot;main&quot;<br>            ],<br>            &quot;cron&quot;: [<br>                &quot;0 0 * * *&quot;  # replace your cron<br>            ],<br>        }<br>    }<br>def build_and_deploy_site_pipeline():<br>    return {<br>        &quot;kind&quot;: &quot;pipeline&quot;,<br>        &quot;type&quot;: &quot;{your_pipeline_type}&quot;,  # docker, kubernetes ...<br>        &quot;name&quot;: &quot;build-and-deploy-site&quot;,<br>        <br>        &quot;steps&quot;: [<br>            {<br>                &quot;name&quot;: &quot;build-site&quot;,<br>                &quot;image&quot;: &quot;python:3.9&quot;,<br>                &quot;commands&quot;: [<br>                    &quot;pip install mkdocs mkdocs-material&quot;,<br>                    &quot;mkdocs build&quot;<br>                ]<br>            },<br>            {<br>                &quot;name&quot;: &quot;deploy&quot;,<br>                &quot;image&quot;: &quot;node:14&quot;,<br>                &quot;environment&quot;: {<br>                    &quot;CLOUDFLARE_API_TOKEN&quot;: {&quot;from_secret&quot;: &quot;cloudflare_api_token&quot;},<br>                    &quot;CLOUDFLARE_ACCOUNT_ID&quot;: {&quot;from_secret&quot;: &quot;cloudflare_account_id&quot;}<br>                },<br>                &quot;commands&quot;: [<br>                    &quot;npm install -g wrangler&quot;,<br>                    &quot;npx wrangler pages deploy --branch {your_cf_branch_name}&quot;<br>                ]<br>            }<br>        ],<br>        <br>        &quot;trigger&quot;: {<br>            &quot;branch&quot;: [<br>                &quot;main&quot;<br>            ],<br>            &quot;cron&quot;: [<br>                &quot;0 0 * * *&quot;  # replace your cron<br>            ]<br>        }<br>    }<br>def main(ctx):<br>    return [<br>        generate_docs_pipeline(),<br>        build_and_deploy_site_pipeline()<br>    ]</pre><p>You can use the <strong><em>Drone CLI</em></strong> to <strong><em>convert</em></strong> a <strong><em>Starlark file</em></strong> to <strong><em>YAML</em></strong>. Then, <strong><em>configure</em></strong> the <strong><em>Drone server</em></strong> to <strong><em>activate</em></strong> the <strong><em>repository</em></strong> using the <strong><em>.drone.yml </em></strong>file.</p><pre>drone starlark --stream --source .drone.star --target .drone.yml --format yaml</pre><h4>Step 4: Configure wrangler.toml</h4><p>Create or update the wrangler.toml file in your repository root:</p><pre>name = &quot;your_project_name&quot;<br>pages_build_output_dir = &quot;./site&quot;<br></pre><p>Replace &quot;your_cloudflare_account_id&quot; and &quot;your_cloudflare_api_token&quot; with your actual Cloudflare account ID and API token.</p><h4>Step 5: Store Cloudflare Secrets in Drone CI</h4><p>Make sure to add the CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID as secrets in your Drone CI repository settings.</p><h3>Putting It All Together</h3><p>Push your changes to your Git repository. Drone CI will automatically trigger the pipelines based on the branch and cron schedule, generating the database documentation, building the static site, and deploying it to Cloudflare Pages. Your database schema documentation is now live and will update automatically based on the configured triggers.</p><h3>Conclusion</h3><p>Automating the creation and deployment of database schema documentation can save time and reduce errors. By integrating <strong><em>tbls</em></strong>, <strong><em>Drone CI</em></strong> using Starlark, <strong><em>MkDocs</em></strong> with the Material theme, and <strong><em>Cloudflare Pages</em></strong>, you can ensure your documentation is always up-to-date and visually appealing. Happy documenting!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f46fd8b80f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining Django REST Framework Serializers with the Dynamic Serializer Decorator]]></title>
            <link>https://medium.com/@joloiuy/streamlining-django-rest-framework-serializers-with-the-dynamic-serializer-decorator-486d03c513f2?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/486d03c513f2</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[serializers]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 11:14:41 GMT</pubDate>
            <atom:updated>2023-12-18T11:14:41.446Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbF7147uL4KbaMPPh1cBww.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@momentsbygabriel?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Gabriel Crismariu</a> on <a href="https://unsplash.com/photos/timelapse-photography-of-road-R9IakPChljQ?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In modern web development, APIs play a crucial role, and Django REST Framework (DRF) has emerged as a popular choice for crafting API endpoints in Django applications. However, as APIs grow in complexity, the need for more flexible and dynamic serializers becomes evident. This is where the concept of a “Dynamic Serializer” shines, offering a customizable way to handle data serialization. In this article, we will explore the ‘dynamic_serializer’ decorator, a custom approach to enhance the functionality of DRF serializers.</p><h3>Understanding the Need for Dynamic Serialization</h3><p>In a typical DRF application, serializers dictate how data is converted to and from JSON format. But what if you need different fields from the same model for different API endpoints? Creating multiple serializers for each variation is not just cumbersome but also violates the DRY (Don’t Repeat Yourself) principle. The solution? A dynamic approach where you can specify which fields to include at runtime.</p><h3>Introducing the Dynamic Serializer Decorator</h3><p>The dynamic decorator wraps around a standard DRF serializer class and allows specifying which fields to include in the serializer at runtime. This approach adds a layer of flexibility, letting you tailor the data representation as per your API&#39;s current context.</p><h3>How It Works</h3><p>Here’s the breakdown of the dynamic decorator:</p><pre>def dynamic(serializer_class):<br>    class SerializerWithDynamicFields(serializer_class):<br>        def __init__(self, *args, **kwargs):<br>            fields = kwargs.pop(&#39;fields&#39;, None)<br><br>            super().__init__(*args, **kwargs)<br>            if fields is not None:<br>                allowed_fields = set(fields)<br>                existing_fields = set(self.fields)<br>                for field_name in existing_fields - allowed_fields:<br>                    self.fields.pop(field_name)<br><br>    SerializerWithDynamicFields.__name__ = f&#39;Dynamic{serializer_class.__name__}&#39;<br>    return SerializerWithDynamicFields</pre><p>When you initialize the serializer, you can pass an optional fields argument. This argument is a list of field names you want to include. The decorator modifies the serializer instance to only include these fields.</p><h3>Use Cases and Advantages</h3><h4>Simplified Serializer Management</h4><p>With the dynamic serializer, you can use one serializer for different views or endpoints, reducing redundancy. It’s particularly beneficial in cases where different users or user roles need to see different data sets.</p><h4>Enhanced Flexibility</h4><p>You gain the ability to tailor the output of your API endpoints without creating multiple serializers for each variation, thus adhering to DRY principles.</p><h4>Improved Code Maintenance</h4><p>Maintaining a single serializer for a model is simpler and less error-prone than juggling multiple serializers for different scenarios.</p><h4>Implementing the Dynamic Serializer</h4><p>Here’s how you can use this in a Django REST Framework view:</p><pre>from rest_framework.views import APIView<br>from myapp.models import MyModel<br>from myapp.serializers import MyModelSerializer, dynamic<br><br>class MyDynamicView(APIView):<br>    def get(self, request, *args, **kwargs):<br>        serializer = dynamic(MyModelSerializer)(instance=MyModel.objects.all(), fields=[&#39;name&#39;, &#39;description&#39;])<br>        return Response(serializer.data)</pre><p>In the above example, MyDynamicView uses the dynamic decorator to include only the &#39;name&#39; and &#39;description&#39; fields of MyModel.</p><h3>Conclusion</h3><p>The dynamic serializer decorator for Django REST Framework introduces a pragmatic approach to managing serializers in your web applications. It aligns with the principles of writing clean, maintainable code and offers a more flexible way to deal with API responses. By adopting this pattern, developers can enhance the scalability and maintainability of their DRF applications, making their APIs more adaptable to changing requirements.</p><h3>Reference</h3><ul><li><a href="https://stackoverflow.com/a/23674297">https://stackoverflow.com/a/23674297</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=486d03c513f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harnessing Drone’s CI/CD Superpower with Starlark Templates]]></title>
            <link>https://medium.com/@joloiuy/harnessing-drones-ci-cd-superpower-with-starlark-templates-4ecc35a92644?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ecc35a92644</guid>
            <category><![CDATA[starlark]]></category>
            <category><![CDATA[template]]></category>
            <category><![CDATA[drone-ci]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Thu, 12 Oct 2023 12:09:38 GMT</pubDate>
            <atom:updated>2023-10-12T12:09:38.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*916yfEDbcwqr8ac-vAtNPA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@jeisblack?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Jason Blackeye</a> on <a href="https://unsplash.com/photos/XYrjl3j7smo?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In the continuously evolving world of CI/CD, ensuring a streamlined, maintainable, and adaptable pipeline is crucial. Drone, a lightweight Continuous Delivery platform, not only simplifies CI/CD but also provides a powerful feature called templates. In this article, we’ll delve into Drone’s templating mechanism, especially focusing on Starlark templates, and see how it can boost your CI/CD pipelines.</p><h3>What is Drone?</h3><p>For the uninitiated, Drone is a cloud-native Continuous Delivery platform. With integrations for popular VCS (Version Control Systems) like GitHub, GitLab, and Bitbucket, Drone stands out due to its speed, simplicity, and an array of plugins that extend its capabilities.</p><h3>Why Starlark for Drone Templates?</h3><p>Starlark, a dialect of Python, is designed to be embedded in Go applications. The use of Starlark in Drone templates provides users with a familiar syntax, bringing the power of a scripting language into the world of CI/CD configurations.</p><h3>Crafting Your Starlark Templates:</h3><h4>1. Using Drone Templates with Starlark:</h4><p>To use a template in Drone with Starlark, set the kind to &#39;template&#39;. Then, define the base template you want to load and your desired inputs. Here&#39;s how it&#39;s done:</p><pre>kind: template<br>load: plugin.starlark<br>data:<br>  stepName: my_step<br>  image: my_image<br>  commands: my_command</pre><h4>2. Designing the Base Template:</h4><p>The base template leverages the power of Starlark. Here’s a simple example:</p><pre>def main(ctx):<br>  return {<br>    &quot;kind&quot;: &quot;pipeline&quot;,<br>    &quot;name&quot;: &quot;build&quot;,<br>    &quot;steps&quot;: [<br>      {<br>        &quot;name&quot;: ctx.input.stepName,<br>        &quot;image&quot;: ctx.input.image,<br>        &quot;commands&quot;: [<br>            ctx.input.commands<br>        ]<br>      }<br>    ]<br>  }</pre><h4>3. Variables in Drone Templates:</h4><p>Drone provides a set of predefined variables that can be leveraged within templates to make them dynamic and context-aware. The complete list of available variables can be found <a href="https://docs.drone.io/template/variables">here</a>.</p><h4>4. Organizing Templates:</h4><p>For larger teams or organizations, centralizing and managing templates is crucial. With Drone’s command-line tools, you can easily manage your organization’s templates:</p><pre>$ drone template add [namespace] [name] [data]<br>$ drone template add octocat template_name @path_to_file</pre><p>This makes it easier to standardize CI/CD configurations across projects, ensuring consistency and reducing redundancy.</p><h3>Why Opt for Starlark Templates in Drone?:</h3><ul><li><strong>Flexibility</strong>: With a scripting language at your disposal, the potential customizations are vast.</li><li><strong>Consistency</strong>: Using templates ensures a uniform CI/CD process across projects and teams.</li><li><strong>Reusability</strong>: Define once, use everywhere! Minimize redundancy and enhance maintainability.</li><li><strong>Dynamic Configurations</strong>: With the power of predefined variables, templates can adjust based on the context, making your pipelines smarter.</li></ul><h3>Conclusion:</h3><p>Starlark templates in Drone elevate the way you handle CI/CD configurations. They combine the power of a scripting language with the efficiency of templates, allowing for dynamic, maintainable, and streamlined pipelines. As projects grow and CI/CD requirements evolve, such tools become indispensable. Dive into Starlark templates with Drone, and experience a new dimension of CI/CD excellence!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ecc35a92644" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Efficient API Development with Go-Swagger]]></title>
            <link>https://blog.stackademic.com/unlocking-efficient-api-development-with-go-swagger-e805329ccbd7?source=rss-197c359c83d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e805329ccbd7</guid>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[swagger]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[KH Huang]]></dc:creator>
            <pubDate>Mon, 09 Oct 2023 12:52:27 GMT</pubDate>
            <atom:updated>2023-10-11T01:16:46.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lQw1Een3VC3LvACs2cVWaw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mariogogh?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Mario Gogh</a> on <a href="https://unsplash.com/photos/RQz0LQSysh0?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>APIs have revolutionized the way we build and interact with software. In the vast landscape of API tools, Go-Swagger stands out as a powerful suite for building and using APIs within the Go (Golang) ecosystem. Stemming from the widely-used Swagger (OpenAPI) specification, Go-Swagger provides an end-to-end solution for Golang developers to describe, build, and consume RESTful services.</p><p>In this article, we’ll unpack the capabilities of Go-Swagger, walk through its key features, and see how it can elevate your Go API development workflow.</p><h3>Understanding the Swagger (OpenAPI) Specification</h3><p>Swagger, now known as OpenAPI, is a specification for building APIs. OpenAPI allows developers to define APIs in a standardized way, using a language-agnostic description. This description can then serve many purposes: documentation, client SDK generation, server stub generation, and more.</p><h3>Introduction to Go-Swagger</h3><p>Go-Swagger brings the power of Swagger to the Go community. It’s an implementation of the OpenAPI 2.0 specification, tailored for the Go language. With Go-Swagger, you can generate powerful APIs that are idiomatic to Go, right from an OpenAPI spec.</p><h3>Installing Go-Swagger</h3><p>Before diving deep, let’s get Go-Swagger up and running (For mac user):</p><pre>brew tap go-swagger/go-swagger<br>brew install go-swagger</pre><h3>Core Features and Benefits</h3><h4>1. API Design First Approach:</h4><p>With Go-Swagger, you start by designing your API using the Swagger 2.0 specification in a YAML or JSON file. This design-first approach ensures that you think about the API’s contract before diving into the code, leading to better-designed and more consistent APIs.</p><h4>2. Automatic Generation of Go Code:</h4><p>Once your API spec is ready, you can auto-generate both the server and client code:</p><pre>swagger generate server -A your_app_name -f ./path_to_your_spec</pre><p>This feature eliminates manual boilerplate, ensuring faster development cycles and less room for human error.</p><h4>3. Interactive API Documentation:</h4><p>One of the most loved features of Swagger is the interactive documentation it provides. Go-Swagger retains this feature, allowing users to understand and test your API endpoints interactively via a UI.</p><h4>4. Validation:</h4><p>Go-Swagger offers robust validation out of the box. Any incoming requests are automatically validated against the OpenAPI spec, ensuring that the inputs match the expected formats and types.</p><h4>5. Customization and Flexibility:</h4><p>While Go-Swagger provides sensible defaults, it doesn’t bind you to them. You have the flexibility to customize routes, adopt a different folder structure, or use a different middleware.</p><h4>6. Middleware Integration:</h4><p>Go-Swagger integrates seamlessly with popular Go middleware, ensuring that you can build powerful, feature-rich APIs without reinventing the wheel.</p><h3>Real-world Usage and Best Practices</h3><p>Using Go-Swagger, many organizations have streamlined their API development processes. Here are some best practices:</p><ul><li>Maintain Your Spec: The OpenAPI spec is the single source of truth. Regularly update it as your API evolves.</li><li>Automate Code Generation: Integrate Go-Swagger into your CI/CD pipelines to ensure that any changes to the spec automatically regenerate the necessary code.</li><li>Embrace Versioning: APIs evolve. Use versioning in your API paths or headers to ensure backward compatibility.</li></ul><h3>Wrapping Up</h3><p>In the modern API-driven world, tools like Go-Swagger are not just luxuries — they’re essentials. They ensure rapid development, consistent design, and robust performance. Whether you’re a startup or an enterprise, if you’re developing APIs in Go, Go-Swagger can be a game-changer. Dive in, and elevate your API game!</p><h3>Stackademic</h3><p><em>Thank you for reading until the end. Before you go:</em></p><ul><li><em>Please consider </em><strong><em>clapping</em></strong><em> and </em><strong><em>following</em></strong><em> the writer! 👏</em></li><li><em>Follow us on </em><a href="https://twitter.com/stackademichq"><strong><em>Twitter(X)</em></strong></a><em>, </em><a href="https://www.linkedin.com/company/stackademic"><strong><em>LinkedIn</em></strong></a><em>, and </em><a href="https://www.youtube.com/c/stackademic"><strong><em>YouTube</em></strong></a><strong><em>.</em></strong></li><li><em>Visit </em><a href="http://stackademic.com/"><strong><em>Stackademic.com</em></strong></a><em> to find out more about how we are democratizing free programming education around the world.</em></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e805329ccbd7" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/unlocking-efficient-api-development-with-go-swagger-e805329ccbd7">Unlocking Efficient API Development with Go-Swagger</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>