<?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 Aslı Kök on Medium]]></title>
        <description><![CDATA[Stories by Aslı Kök on Medium]]></description>
        <link>https://medium.com/@imgeaslikok?source=rss-ca11dd4e8233------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aCmp_ym0iC3QBCExOF-6SQ.jpeg</url>
            <title>Stories by Aslı Kök on Medium</title>
            <link>https://medium.com/@imgeaslikok?source=rss-ca11dd4e8233------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:00:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imgeaslikok/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[The Hidden Bug Between DB Commit and Queue Enqueue]]></title>
            <link>https://medium.com/@imgeaslikok/the-bug-between-db-commit-and-queue-enqueue-c8ef92207863?source=rss-ca11dd4e8233------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ef92207863</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Aslı Kök]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 18:37:20 GMT</pubDate>
            <atom:updated>2026-03-10T09:51:00.375Z</atom:updated>
            <content:encoded><![CDATA[<h4>How the Transactional Outbox pattern prevents silent job loss in distributed systems</h4><p>There’s a bug hiding in almost every backend I’ve worked on.</p><p>It lives in the gap between two lines of code:</p><pre>db.commit()<br><br>queue.enqueue()</pre><p>At first glance, nothing seems wrong</p><p>You write the job to the database. <br>Then you push it to the queue.</p><p>Simple.</p><p>Except those two operations are not atomic.</p><p>And one day, usually during a deploy, a container restart, or a kernel OOM, the process crashes between them.</p><p>The result?</p><p>The job row exists in the database.</p><p>But the task was never sent to the queue.</p><p>No error.</p><p>No retry.</p><p>Just a job that will never run.</p><p>And unless you’re explicitly looking for it, you might never notice.</p><p>In this post, I’ll walk through a background job pipeline I built in Python to close that gap, along with a few other reliability holes that tend to appear in distributed systems.</p><p>The system uses <strong>FastAPI</strong>, <strong>Celery</strong>, and <strong>PostgreSQL</strong>, but the ideas translate anywhere. I’ll focus on the specific decisions that move a naive queue integration toward something you’d actually trust in production.</p><h3>The Core Problem</h3><p>When you need background work to happen reliably, the naive approach of writing the record and then enqueueing the task has a race condition baked in.</p><p>The write and the enqueue are <strong>not atomic</strong>. One can succeed without the other.</p><p>The solution isn’t to retry the enqueue harder.</p><p>The solution is to <strong>never separate them in the first place.</strong></p><p>The pattern that solves this is called the <strong>Transactional Outbox</strong>.</p><p>Instead of calling the broker directly, you write a dispatch event to the <strong>same database</strong>, in the <strong>same transaction</strong> as your domain record.</p><p>A separate process, a Celery Beat task in this case, reads those events and publishes them to the broker.</p><p>If the process crashes before publishing, the event is still in the database and gets picked up on the next tick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKtruZsT3NtXnO3z_ppvSQ.png" /><figcaption>Background Job Pipeline Overview</figcaption></figure><p>The submission path ends up looking like this:</p><pre>def submit_job(uow, *, job_type, payload, idempotency_key=None, request_id=None):<br>    job = _create_job_row(uow.session, job_type=job_type, payload=payload, ...)<br>    outbox_service.create_event(<br>        uow.session,<br>        event_type=JOB_DISPATCH_REQUESTED,<br>        payload={&quot;job_id&quot;: job.id, &quot;request_id&quot;: request_id},<br>    )<br>    return job</pre><p>Both writes happen inside the caller’s <strong>UnitOfWork</strong>.</p><p>They commit together or roll back together.</p><p>The broker never sees the job until the database has confirmed it exists.</p><p>The cost is latency. In this setup the delay can be up to 2 seconds (one Beat tick). For most job workloads, that is a reasonable trade-off.</p><h3>The Outbox Publisher: Two-Phase Processing</h3><p>The publisher runs every <strong>2 seconds</strong> and has a subtle design worth explaining.</p><p>It works in <strong>two phases</strong>.</p><h4>Phase 1: Claim Events</h4><p>Claim a batch of event IDs using:</p><pre>SELECT ... FOR UPDATE SKIP LOCKED</pre><p>Then immediately commit to release the row locks.</p><h4>Phase 2 : Publish Events</h4><p>For each ID:</p><ul><li>open a new session</li><li>re-acquire the lock</li><li>verify the event is still pending</li><li>dispatch to Celery</li><li>commit the event independently</li></ul><pre>while True:<br>    with session_factory() as db:<br>        event_ids = repo.get_pending_batch_ids(db, now=now_utc(), limit=limit)<br>        db.commit()<br>    for event_id in event_ids:<br>        with session_factory() as db:<br>            event = repo.get_for_update(db, id=event_id)<br>            if event is None or event.status != OutboxStatus.PENDING:<br>                continue<br>            _publish_single_event(db, event=event, dispatch_job=dispatch_job)<br>            db.commit()</pre><p>This design matters because <strong>failure becomes local</strong>.</p><p>If publishing event N fails, events N+1 through M are unaffected.</p><p>Each event commits independently.</p><p>It also handles backlog: if the batch is full, the publisher loops immediately instead of waiting for the next Beat tick.</p><h3>Concurrency Safety Without a Distributed Lock</h3><p>When a worker starts a job, the first step is acquiring a <strong>row-level lock</strong>.</p><pre>def begin_attempt(db, *, job_id, started_at):<br>    job = repo.get_for_update(db, id=job_id)<br>    if _is_terminal(job.status):<br>        return AttemptResult(False, &quot;terminal&quot;, job, None)<br>    attempt_no = int(job.attempts or 0) + 1<br>    job.status = JobStatus.RUNNING<br>    job.attempts = attempt_no<br>    attempt = JobAttempt(job_id=job.id, attempt_no=attempt_no, status=RUNNING, ...)<br>    db.add(attempt)<br>    try:<br>        db.flush()<br>    except IntegrityError:<br>        return AttemptResult(False, &quot;duplicate&quot;, job, None)<br>    return AttemptResult(True, None, job, attempt_no)</pre><p>This protects against <strong>two failure modes</strong>.</p><h4>1. Concurrent workers</h4><p>SELECT FOR UPDATE ensures only one worker can run the job.</p><h4>2. Duplicate attempts</h4><p>A database constraint enforces uniqueness:</p><pre>UNIQUE(job_id, attempt_no)</pre><p>If two workers somehow attempt execution simultaneously, one flush succeeds, and the other fails with IntegrityError.</p><p>The duplicate worker exits safely.</p><p>Using <strong>PostgreSQL row locks</strong> instead of Redis distributed locks simplifies everything.</p><p>Database locks are:</p><ul><li>transactional</li><li>crash-safe</li><li>automatically released</li></ul><p>No TTL management.<br>No heartbeats.<br>No extra infrastructure.</p><h3>The Executor Registry</h3><p>The pipeline is domain-agnostic.</p><p>Domains register executors:</p><pre>@register(&quot;reports.generate&quot;)<br>def generate_report(ctx: JobContext, payload: dict) -&gt; ExecutionResult:<br>    report_id = payload[&quot;report_id&quot;]<br>    result = _build_result(report_id=report_id, ctx=ctx)<br>    try:<br>        complete_report(ctx.uow, report_id=report_id, result=result)<br>    except ReportNotFound as e:<br>        raise NonRetryableJobError(str(e)) from e<br>    except SQLAlchemyError as e:<br>        raise RetryableJobError(&quot;DB failure persisting result&quot;) from e<br>    return ExecutionResult(result=result)</pre><p>At worker startup, the executor modules are imported, registering themselves via decorators.</p><p>Dispatch becomes a simple dictionary lookup.</p><p>Executors receive a JobContext containing:</p><ul><li>uow</li><li>job_id</li><li>attempt_no</li><li>request_id</li></ul><p>Domain updates and job completion happen inside <strong>the same transaction</strong>.</p><h3>Error Classification as a First-Class Contract</h3><p>Executors communicate failure by raising typed exceptions.</p><pre>raise RetryableJobError(&quot;Redis unavailable&quot;)<br>raise NonRetryableJobError(&quot;Missing required payload field&quot;)</pre><p>The pipeline classifies errors:</p><pre>def _classify_execution_error(exc, *, current_retries, max_retries):<br>    if isinstance(exc, (ExecutorNotRegistered, NonRetryableJobError)):<br>        return DEAD<br>    if isinstance(exc, RetryableJobError):<br>        if current_retries &gt;= max_retries:<br>            return DEAD<br>        return RETRY<br>    raise exc</pre><p>Unexpected errors propagate and cause Celery to <strong>nack the message</strong>, forcing a retry.</p><h3>Finalization Under a Savepoint</h3><p>Executors run inside the job transaction.</p><p>But finalization itself could fail.</p><p>If it does, we don’t want to lose the executor’s domain work.</p><p>The solution: <strong>savepoints</strong>.</p><pre>with db.begin_nested():<br>    pipeline.finalize_attempt(...)</pre><p>If finalization fails:</p><ul><li>the savepoint rolls back</li><li>the outer transaction survives</li><li>domain changes remain</li></ul><p>The job may be left in RUNNING.</p><p>That’s where the <strong>sweeper</strong> comes in.</p><h3>The Sweeper: Recovery Without a Human</h3><p>A periodic task scans for stuck jobs.</p><pre>def reset_stuck_running_jobs(db, *, max_execution_seconds):<br>    stuck_before = now_utc() - timedelta(seconds=max_execution_seconds)<br>    jobs = repo.list_stuck_running(db, stuck_before=stuck_before)<br>    for job in jobs:<br>        job.status = JobStatus.PENDING<br>        outbox_service.create_event(...)</pre><p>Jobs stuck in RUNNING are reset and re-dispatched automatically.</p><p>No manual intervention required.</p><h3>Idempotency at Two Levels</h3><p>The system prevents duplicates in two ways.</p><h4>Job Submission</h4><p>A partial unique index:</p><pre>UNIQUE(idempotency_key) WHERE NOT NULL</pre><p>Submission logic handles races with an IntegrityError fallback.</p><h4>Job Execution</h4><p>A database constraint:</p><pre>UNIQUE(job_id, attempt_no)</pre><p>Prevents duplicate task execution.</p><h3>Retries: Full Jitter Beats Fixed Backoff</h3><p>Retry delays use <strong>full jitter</strong>.</p><pre>def retry_countdown(current_retries: int) -&gt; int:<br>    max_delay = min(cap, base * (backoff_base ** current_retries))<br>    return random.randint(0, int(max_delay))</pre><p>This spreads retries across a window and avoids retry storms when many jobs fail simultaneously.</p><h3>Request Correlation Across the Async Chain</h3><p>The X-Request-Id header flows through the entire pipeline:</p><pre>HTTP request<br>→ outbox event<br>→ Celery task headers<br>→ worker logs</pre><p>Workers extract it from task headers:</p><pre>headers = getattr(task.request, &quot;headers&quot;, None) or {}<br>request_id = headers.get(&quot;X-Request-Id&quot;)</pre><p>This enables end-to-end tracing in logs without distributed tracing infrastructure.</p><h3>Trade-offs Worth Calling Out</h3><h4>Dispatch latency</h4><p>The outbox introduces up to <strong>2 seconds</strong> delay.</p><h4>Beat is a scheduling SPOF</h4><p>Run exactly <strong>one Beat instance</strong>.</p><h4>Long transactions</h4><p>Executors hold a DB transaction during execution.</p><p>Avoid long external operations inside the UnitOfWork.</p><h4>At-least-once delivery</h4><p>Duplicate dispatches are possible but safe due to database constraints.</p><h3>Practical Takeaways</h3><p>If I had to summarize:</p><ul><li>Write dispatch events in the same transaction as the domain record.</li><li>Use your <strong>database for coordination</strong>, not distributed locks.</li><li>Make executors <strong>classify errors explicitly</strong>.</li><li>Add a <strong>sweeper</strong> to recover stuck jobs.</li><li>Use <strong>savepoints</strong> for optional writes.</li><li>Prefer <strong>full jitter</strong> retry strategies.</li><li>Propagate <strong>request IDs</strong> across async boundaries.</li></ul><h3>TL;DR</h3><p>If you run background jobs in production:</p><ul><li>Write dispatch events in the same transaction as the job record</li><li>Use PostgreSQL row locks instead of distributed locks</li><li>Make executor errors explicit (retryable vs permanent)</li><li>Add a sweeper to recover stuck jobs</li></ul><p>These small decisions turn a fragile queue integration into a reliable job system.</p><h3>Conclusion</h3><p>The gap between:</p><pre>db.commit()<br>queue.enqueue()</pre><p>is small.</p><p>But one unlucky crash can leave a job permanently lost.</p><p>The <strong>Transactional Outbox</strong> closes that gap.</p><p>The rest — row locks, savepoints, sweepers, typed exceptions — are the engineering details that make a system behave correctly when things go wrong.</p><p>None of these techniques are individually complex.</p><p>But together they turn a fragile queue integration into a background job system you can actually trust in production.</p><p>If you’re interested in the full implementation, the source code is available here:</p><p><a href="https://github.com/imgeaslikok/deterministic-job-pipeline">https://github.com/imgeaslikok/deterministic-job-pipeline</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ef92207863" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrency Safety in Django: Preventing Race Conditions with Advisory Locks]]></title>
            <link>https://medium.com/production-ready-django/concurrency-safety-in-django-preventing-race-conditions-with-advisory-locks-18d436783a98?source=rss-ca11dd4e8233------2</link>
            <guid isPermaLink="false">https://medium.com/p/18d436783a98</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Aslı Kök]]></dc:creator>
            <pubDate>Mon, 09 Mar 2026 12:44:29 GMT</pubDate>
            <atom:updated>2026-03-09T13:08:43.014Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical pattern for serializing state transitions in Django APIs using PostgreSQL advisory locks</h4><p>Concurrency bugs are some of the most expensive bugs in production systems.</p><p>They often appear rarely and only under load, which makes them difficult to reproduce and debug.</p><p>Typical examples include:</p><ul><li>two requests updating the same record</li><li>inconsistent state transitions</li><li>lost updates</li></ul><p>TaskBase prevents these issues using <strong>database-level concurrency control</strong> built on PostgreSQL advisory locks.</p><p>This article shows how that pattern works.</p><h3>The Race Condition Problem</h3><p>Consider a simple task status update.</p><p>Two clients send requests at the same time:</p><pre>PATCH /tasks/123/status</pre><p>If both requests read the same state and write a new value, the final result can depend on timing.</p><p>Without concurrency control, you can get inconsistent results.</p><h3>Domain-Level State Transitions</h3><p>In TaskBase, state changes are implemented in <strong>use-cases</strong>, not inside DRF views.</p><p>Example:</p><pre>transition_task_status(task=task, to_status=&quot;completed&quot;)</pre><p>This function performs the entire state transition.</p><p>This separation ensures that:</p><ul><li>business rules stay outside the API layer</li><li>concurrency rules can be applied consistently</li></ul><h3>PostgreSQL Advisory Locks</h3><p>TaskBase uses a small library built on PostgreSQL advisory locks:</p><p><a href="https://github.com/imgeaslikok/django-concurrency-safe">https://github.com/imgeaslikok/django-concurrency-safe</a></p><p>Advisory locks allow the application to serialize operations on specific resources.</p><p>Instead of locking a database row automatically, the application chooses the lock key.</p><p>For task transitions, the decorator receives a key template.<br>The library formats it using the function arguments.</p><p>The lock key template used in TaskBase looks like this:</p><pre>taskbase:task:{task.pk}:transition:status</pre><p>This ensures that only one status transition for a given task can run at a time.</p><h3>Concurrency-Safe State Transitions</h3><p>The transition function is decorated with concurrency_safe.</p><pre>@concurrency_safe(<br>    key=TASK_STATUS_LOCK_KEY_TEMPLATE,<br>    timeout=1.0,<br>    on_conflict=_raise_task_conflict,<br>)<br>def transition_task_status(*, task: Task, to_status: str):</pre><p>This decorator:</p><ol><li>acquires an advisory lock</li><li>runs the function</li><li>releases the lock automatically</li></ol><p>If another request already holds the lock, the decorator calls the on_conflict handler.</p><h3>Converting Lock Conflicts into Domain Errors</h3><p>Instead of exposing database errors to the API layer, TaskBase converts lock failures into domain exceptions.</p><pre>def _raise_task_conflict(*_args, **_kwargs):<br>    raise TaskConcurrencyError(<br>        &quot;Task is being updated concurrently. Please retry.&quot;<br>    )</pre><p>This keeps concurrency concerns inside the domain layer.</p><p>The API layer simply returns a structured error response.</p><h3>Refreshing State After Lock Acquisition</h3><p>Another important detail appears inside the transition function:</p><pre>task.refresh_from_db(fields=[&quot;status&quot;, &quot;deleted_at&quot;, &quot;updated_at&quot;])</pre><p>This ensures the function reads the <strong>latest database state after acquiring the lock</strong>.</p><p>Without this step, stale in-memory objects could overwrite newer data.</p><h3>Idempotent State Transitions</h3><p>The function also supports idempotent behavior.</p><pre>if task.status == to_status:<br>    return TransitionTaskStatusResult(task=task, idempotent=True)</pre><p>If the task is already in the desired state, the function exits without writing to the database.</p><p>Idempotency is extremely useful in distributed systems where retries are common.</p><h3>Why Not Use Row Locks?</h3><p>Another common approach is:</p><pre>select_for_update()</pre><p>This works well inside explicit database transactions.</p><p>TaskBase instead uses advisory locks because they:</p><ul><li>do not require holding database transactions open</li><li>allow flexible lock keys</li><li>avoid accidentally locking large query sets</li></ul><p>They also integrate cleanly with domain-level operations.</p><h3>Concurrency Safety as a First-Class Concern</h3><p>In many applications, concurrency control is added only after bugs appear in production.</p><p>TaskBase treats it as a core design concern.</p><p>By combining:</p><ul><li>domain-level use-cases</li><li>advisory locks</li><li>idempotent transitions</li></ul><p>the system ensures that state changes remain consistent even under concurrent requests.</p><p>Full source code:</p><p><a href="https://github.com/imgeaslikok/taskbase-api">https://github.com/imgeaslikok/taskbase-api</a></p><p>Concurrency library:</p><p><a href="https://github.com/imgeaslikok/django-concurrency-safe">https://github.com/imgeaslikok/django-concurrency-safe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18d436783a98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/production-ready-django/concurrency-safety-in-django-preventing-race-conditions-with-advisory-locks-18d436783a98">Concurrency Safety in Django: Preventing Race Conditions with Advisory Locks</a> was originally published in <a href="https://medium.com/production-ready-django">Production-Ready Django</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fast List Endpoints in Django: Query Optimization and Safe Response Caching]]></title>
            <link>https://medium.com/production-ready-django/fast-list-endpoints-in-django-query-optimization-and-safe-response-caching-5f5e1e8d3eb7?source=rss-ca11dd4e8233------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f5e1e8d3eb7</guid>
            <dc:creator><![CDATA[Aslı Kök]]></dc:creator>
            <pubDate>Sun, 08 Mar 2026 17:16:07 GMT</pubDate>
            <atom:updated>2026-03-08T17:18:53.447Z</atom:updated>
            <content:encoded><![CDATA[<h4>Making list endpoints fast without premature complexity</h4><p>Most backend performance problems start the same way.</p><p>An endpoint that used to be fast suddenly becomes slow.</p><p>The usual reaction is to add caching immediately.<br>But caching without understanding query performance often creates new problems instead of solving the original one.</p><p>In TaskBase, the performance strategy follows a simple rule:</p><p><strong>Optimize queries first. Cache second.</strong></p><p>This article shows the patterns used in the TaskBase API.</p><h3>Query Optimization Comes First</h3><p>Before introducing caching, it’s important to ensure database queries are efficient.</p><p>A common issue in Django APIs is the <strong>N+1 query problem</strong>.</p><p>Example:</p><pre>projects = Project.objects.all()<br><br>for project in projects:<br>    print(project.owner.email)</pre><p>If owner is a foreign key; this can result in <strong>one query per project</strong>.</p><p>Instead, Django provides query optimization tools such as:</p><ul><li>select_related</li><li>prefetch_related</li></ul><p>These allow related objects to be fetched in a single query.</p><p>Example:</p><pre>projects = Project.objects.select_related(&quot;owner&quot;)</pre><p>This simple change often eliminates dozens of unnecessary database queries.</p><h3>When Query Optimization Isn’t Enough</h3><p>Even well-optimized queries can become expensive when an endpoint is called frequently.</p><p>Typical examples:</p><ul><li>project lists</li><li>dashboards</li><li>filtered search endpoints</li></ul><p>For these cases, TaskBase adds <strong>response-level caching</strong>.</p><p>But caching API responses must be done carefully.</p><p>Two common mistakes are:</p><ol><li><strong>Tenant leaks</strong> — users seeing cached data belonging to another user</li><li><strong>Incorrect cache keys</strong> — ignoring query parameters</li></ol><p>TaskBase solves this by building cache keys that include both the user and the request path.</p><h3>Caching API List Responses Safely</h3><p>TaskBase uses a small decorator to cache list responses.</p><pre>def cache_list_response(*, ttl: int, prefix: str):</pre><p>The decorator generates a cache key using:</p><ul><li>the user id</li><li>the full request path (including query parameters)</li></ul><p>Example key structure:</p><pre>projects:user=42:path=/api/v1/projects/?page=1&amp;ordering=name</pre><p>To keep cache keys short and consistent, the key is hashed.</p><pre>raw_key = f&quot;{prefix}:user={request.user.id}:path={request.get_full_path()}&quot;<br>cache_key = f&quot;api:{hashlib.sha256(raw_key.encode(&#39;utf-8&#39;)).hexdigest()}&quot;</pre><p>This guarantees that:</p><ul><li>different users never share cached responses</li><li>different query parameters produce different cache entries</li></ul><h3>The Caching Decorator</h3><p>The decorator wraps a DRF view method.</p><pre>cached = cache.get(cache_key)<br><br>if cached is not None:<br>    return Response(cached)</pre><p>If the response is already cached, it returns immediately.</p><p>Otherwise, the view executes normally.</p><pre>response = view_method(self, request, *args, **kwargs)<br><br>if response.status_code == 200:<br>    cache.set(cache_key, response.data, timeout=ttl)</pre><p>Only successful responses are cached.</p><p>This prevents errors from being stored in the cache.</p><h3>Why Cache Only the Response Data</h3><p>The decorator stores <strong>response.data</strong>, not the full response object.</p><p>This avoids problems with:</p><ul><li>renderer state</li><li>headers</li><li>serialization artifacts</li></ul><p>It also keeps the cache format simple and portable.</p><h3>Cache Keys Must Capture Query Parameters</h3><p>One important detail is the use of:</p><pre>request.get_full_path()</pre><p>This includes query parameters such as:</p><pre>?page=2<br>?search=test<br>?ordering=name</pre><p>Without this, different queries could incorrectly share the same cached response.</p><h3>Choosing the Right TTL</h3><p>The decorator requires an explicit TTL:</p><pre>@cache_list_response(ttl=60, prefix=&quot;projects&quot;)</pre><p>Short TTL values are usually best for API endpoints.</p><p>Typical ranges:</p><ul><li>30 seconds</li><li>60 seconds</li><li>120 seconds</li></ul><p>Short-lived caches reduce stale data problems while still absorbing bursts of traffic.</p><h3>Optimize First, Cache Second</h3><p>TaskBase follows a simple performance strategy:</p><ol><li>Fix inefficient queries</li><li>Ensure correct database indexes</li><li>Add response caching where needed</li></ol><p>Caching should not be the first step.</p><p>When used carefully, however, a small caching layer can dramatically reduce database load for high-traffic endpoints.</p><h3>What Comes Next</h3><p>In the next article, we’ll look at a different production concern:</p><p><strong>concurrency safety.</strong></p><p>Handling concurrent requests correctly is one of the most common sources of subtle bugs in backend systems.</p><p>Full source code:<br> <a href="https://github.com/imgeaslikok/taskbase-api">https://github.com/imgeaslikok/taskbase-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f5e1e8d3eb7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/production-ready-django/fast-list-endpoints-in-django-query-optimization-and-safe-response-caching-5f5e1e8d3eb7">Fast List Endpoints in Django: Query Optimization and Safe Response Caching</a> was originally published in <a href="https://medium.com/production-ready-django">Production-Ready Django</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observability in Django: Request IDs, Structured Logs, and Error Contracts]]></title>
            <link>https://medium.com/production-ready-django/observability-in-django-request-ids-structured-logs-and-error-contracts-4b1886bd95b1?source=rss-ca11dd4e8233------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b1886bd95b1</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Aslı Kök]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 11:37:51 GMT</pubDate>
            <atom:updated>2026-03-06T11:52:08.749Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to make your backend debuggable in production without adding unnecessary complexity</h4><p>Most backend tutorials focus on features.<br> Production systems spend a surprising amount of time being debugged.</p><p>When something breaks, the first question is not <em>“what endpoint exists?”</em> — it’s <em>“what happened?”</em> and <em>“which request caused it?”</em></p><p>This article shows the minimal observability pattern used in TaskBase: request IDs, structured logs, and a consistent error contract.</p><p>This is not a full observability stack.</p><p>It is the smallest set of primitives that makes a backend debuggable in production.</p><h3>Every Request Needs a Correlation ID</h3><p>If you can’t correlate logs to a specific request, debugging becomes guesswork.</p><p>A request ID is a simple production primitive:</p><ul><li>it’s returned to the client via X-Request-ID</li><li>it appears in logs</li><li>it’s attached to error responses</li></ul><p>TaskBase implements this as middleware.</p><h3>Request ID Middleware (ASGI-Safe)</h3><p>TaskBase stores the request id using <strong>contextvars</strong>, not thread-local storage.</p><p>That detail matters because modern Django deployments can run under <strong>ASGI</strong>, where thread-local context is not reliable.</p><pre>from contextvars import ContextVar<br><br>_request_id_ctx: ContextVar[str | None] = ContextVar(&quot;request_id&quot;, default=None)<br>def get_request_id() -&gt; str | None:<br>    return _request_id_ctx.get()</pre><p>Incoming request IDs are reused when valid (proxy/gateway friendly). Otherwise, a new UUID4-based request id is generated.</p><pre>_REQUEST_ID_RE = re.compile(r&quot;^[A-Za-z0-9\-_.]{8,128}$&quot;)<br><br><br>def _normalize(value: str) -&gt; str | None:<br>    value = (value or &quot;&quot;).strip()<br>    if not value:<br>        return None<br>    return value if _REQUEST_ID_RE.match(value) else None</pre><p>The middleware sets the request id and stores a token so the context can be reliably reset.</p><pre>incoming = request.META.get(&quot;HTTP_X_REQUEST_ID&quot;, &quot;&quot;)<br>request_id = self._normalize(incoming) or uuid.uuid4().hex<br><br>request.request_id = request_id<br><br>request._request_id_token = _request_id_ctx.set(request_id)</pre><p>The same id is returned to the client.</p><pre>request_id = getattr(request, &quot;request_id&quot;, None) or uuid.uuid4().hex<br>response[&quot;X-Request-ID&quot;] = request_id</pre><p>The context is reset to avoid leaks. In production implementations, this typically happens in a finally block so the context is always cleaned up.</p><pre>token = getattr(request, &quot;_request_id_token&quot;, None)<br>if token is not None:<br>    _request_id_ctx.reset(token)</pre><p>This is intentionally simple but production-correct: each request has a stable identity, and the context is safely cleared.</p><h3>Access Logs: Method, Path, Status, Duration (and Request ID)</h3><p>TaskBase logs basic access metadata for every request:</p><ul><li>method</li><li>path</li><li>status code</li><li>duration in milliseconds</li><li>request id</li></ul><pre>duration_ms = int((time.monotonic() - start) * 1000)<br>access_logger.info(<br>    &quot;request method=%s path=%s status=%s duration_ms=%s request_id=%s&quot;,<br>    request.method,<br>    request.path,<br>    response.status_code,<br>    duration_ms,<br>    get_request_id(),<br>)</pre><p>This is the minimum <strong>observability</strong> needed to answer questions like:</p><ul><li>Which endpoint is slow?</li><li>Which requests are failing?</li><li>Can we correlate a client error with a server log?</li></ul><h3>Structured Logs: Make Logs Queryable</h3><p>Plain logs are difficult to <strong>query and filter</strong>.</p><p>TaskBase keeps logs structured by using stable key=value fields in the message instead of free-form log messages, and a log formatter that includes request_id.</p><p>A small logging filter injects request_id into log records:</p><pre>class RequestIdFilter:<br>    def filter(self, record):<br>        record.request_id = get_request_id() or &quot;-&quot;<br>        return True</pre><p>With a formatter like:</p><pre>%(asctime)s %(levelname)s %(name)s request_id=%(request_id)s %(message)s</pre><p>Now you can grep or query logs by request_id and reconstruct a single request&#39;s story.</p><h3>Consistent Error Contracts</h3><p>In production, clients need predictable error responses.</p><p>TaskBase uses a global exception handler (implemented via a Django REST Framework exception handler) to return a consistent shape and include the request id, so a client-side error can be correlated with server logs.</p><p>Example shape:</p><pre>{<br>  &quot;error&quot;: {<br>    &quot;code&quot;: &quot;not_found&quot;,<br>    &quot;message&quot;: &quot;Project not found&quot;,<br>    &quot;request_id&quot;: &quot;abc123&quot;<br>  }<br>}</pre><p>The important part is not the exact schema.</p><p>It’s the guarantee that every error includes a request identifier.</p><h3>Minimal Observability Is a Feature</h3><p>TaskBase intentionally avoids heavy observability infrastructure.</p><p>No tracing platform.<br> No OpenTelemetry pipeline.</p><p>Just a few high-leverage primitives:</p><ul><li>request IDs</li><li>access logs</li><li>structured logs</li><li>consistent error responses</li></ul><p>This is enough to make a backend debuggable without adding unnecessary complexity.</p><h3>What Comes Next</h3><p>In the next article, we’ll cover performance: query optimization patterns and caching.</p><p>Full source code:<br> <a href="https://github.com/imgeaslikok/taskbase-api">https://github.com/imgeaslikok/taskbase-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b1886bd95b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/production-ready-django/observability-in-django-request-ids-structured-logs-and-error-contracts-4b1886bd95b1">Observability in Django: Request IDs, Structured Logs, and Error Contracts</a> was originally published in <a href="https://medium.com/production-ready-django">Production-Ready Django</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Soft Delete in Django Without Extra Complexity]]></title>
            <link>https://medium.com/production-ready-django/soft-delete-in-django-without-extra-complexity-01eea82594a3?source=rss-ca11dd4e8233------2</link>
            <guid isPermaLink="false">https://medium.com/p/01eea82594a3</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Aslı Kök]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 17:10:34 GMT</pubDate>
            <atom:updated>2026-03-06T11:51:51.719Z</atom:updated>
            <content:encoded><![CDATA[<h4>A practical pattern for safe deletions using a timestamp field, a default manager, and an explicit escape hatch</h4><p>In production systems, “delete” is rarely a simple operation.</p><p>Hard deletes can break auditability, remove evidence, and cause accidental data loss — especially when users make mistakes and support teams need recovery.</p><p>This article shows the soft delete approach used in TaskBase: minimal, explicit, and easy to reason about.</p><h3>Why Hard Delete Is Usually a Trap</h3><p>Hard delete means the row is gone.</p><p>That sounds clean, but it creates real operational problems:</p><ul><li>Support can’t recover “accidentally deleted” data</li><li>Audit trails become incomplete</li><li>Cascades can permanently remove related records</li><li>Bugs become destructive instead of reversible</li></ul><p>Soft delete avoids most of these issues by changing the definition of “deleted”:</p><p>Deleted records are not removed.<br>They are marked.</p><h3>The Core Model: deleted_at Timestamp</h3><p>TaskBase uses a single field:</p><pre>class SoftDeleteModel(models.Model):<br>    deleted_at = models.DateTimeField(null=True, blank=True)<br>    <br>    objects = managers.SoftDeleteManager()<br>    all_objects = querysets.SoftDeleteQuerySet.as_manager()<br><br>    class Meta:<br>        abstract = True</pre><p>A record is active if it deleted_at is null.<br>A record is deleted if it contains a timestamp.</p><p>This is intentionally simple.</p><p>No extra tables.<br>No third-party packages.<br>No hidden magic.</p><h3>Delete, Restore, Hard Delete</h3><p>The base model defines three explicit operations.</p><p>Soft delete:</p><pre>def delete(self, using=None, keep_parents=False):<br>    if self.deleted_at is None:<br>        self.deleted_at = timezone.now()<br>        self.save(update_fields=[&quot;deleted_at&quot;])</pre><p>Restore:</p><pre>def restore(self):<br>    if self.deleted_at is not None:<br>        self.deleted_at = None<br>        self.save(update_fields=[&quot;deleted_at&quot;])</pre><p>Hard delete (escape hatch):</p><pre>def hard_delete(self):<br>    return super().delete()</pre><p>This is the important design choice:</p><p>Soft delete is the default.<br>Hard delete is explicit.</p><h3>Enforcing “Active by Default” with the Manager</h3><p>The key to making soft delete safe is not the field.</p><p>It’s the default manager.</p><p>In TaskBase, objects only returns active records:</p><pre>class SoftDeleteManager(models.Manager):<br>    def get_queryset(self):<br>        return SoftDeleteQuerySet(self.model, using=self._db).active()</pre><p>This ensures that:</p><ul><li>every normal query ignores deleted records</li><li>deleted data doesn’t accidentally appear in the API</li><li>developers don’t need to remember to filter manually</li></ul><p>Deleted records are still accessible through a separate manager:</p><pre>all_objects = SoftDeleteQuerySet.as_manager()</pre><p>This creates a clean separation:</p><ul><li>objects → active records</li><li>all_objects → active + deleted (for admin/support/internal flows)</li></ul><h3>QuerySet Support: Bulk Soft Delete</h3><p>Soft delete must also work for bulk operations.</p><p>TaskBase implements it at the queryset level:</p><pre>class SoftDeleteQuerySet(models.QuerySet):<br>    def active(self):<br>        return self.filter(deleted_at__isnull=True)<br>    def deleted(self):<br>        return self.filter(deleted_at__isnull=False)<br>    def delete(self):<br>        return super().update(deleted_at=timezone.now())<br>    def hard_delete(self):<br>        return super().delete()</pre><p>This matters because many code paths call:</p><pre>Model.objects.filter(...).delete()</pre><p>If the queryset delete isn’t overridden, you will accidentally hard delete in production.</p><h3>Example Usage in Domain Models</h3><p>In TaskBase, domain models inherit:</p><pre>class TimeStampedSoftDeleteModel(TimeStampedModel, SoftDeleteModel):<br>    class Meta:<br>        abstract = True</pre><p>Then:</p><ul><li>Project</li><li>Task</li><li>Collaborator</li></ul><p>all gain consistent behavior.</p><p>This is “minimal reuse” done correctly: one shared base, one shared contract.</p><h3>What This Pattern Does Not Solve</h3><p>Soft delete is not free.</p><p>It introduces new questions:</p><ul><li>Should soft-deleting a project soft-delete its tasks and collaborators?</li><li>How do you handle unique constraints when a deleted row still exists?</li><li>Should background cleanup hard-delete old records?</li></ul><p>TaskBase keeps the pattern intentionally minimal and explicit.</p><p>It does not attempt to solve every lifecycle problem upfront.</p><p>That belongs in the domain layer, case by case.</p><h3>Why This Approach Works for a Minimal Guide</h3><p>This design is intentionally small, but it teaches the right production mindset:</p><ul><li>deleting data is a business decision</li><li>safety and recoverability matter</li><li>defaults should be safe</li><li>escape hatches should be explicit</li></ul><p>It scales from small projects to large systems without changing the fundamentals.</p><h3>What Comes Next</h3><p>In the next article, we’ll cover observability: request IDs, logging structure, and a consistent error contract.</p><p>Full source code:</p><p><a href="https://github.com/imgeaslikok/taskbase-api">https://github.com/imgeaslikok/taskbase-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01eea82594a3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/production-ready-django/soft-delete-in-django-without-extra-complexity-01eea82594a3">Soft Delete in Django Without Extra Complexity</a> was originally published in <a href="https://medium.com/production-ready-django">Production-Ready Django</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Authorization Is Architecture: Implementing RBAC in Django]]></title>
            <link>https://medium.com/production-ready-django/authorization-is-architecture-implementing-rbac-in-django-e61bc8e1c54d?source=rss-ca11dd4e8233------2</link>
            <guid isPermaLink="false">https://medium.com/p/e61bc8e1c54d</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Aslı Kök]]></dc:creator>
            <pubDate>Sun, 01 Mar 2026 16:51:11 GMT</pubDate>
            <atom:updated>2026-03-06T11:51:24.685Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to design framework-agnostic authorization using scopes and immutable policy rules</h4><p>Most Django projects start with simple permission checks.</p><p>Over time, authorization logic spreads across views, serializers, and querysets — and becomes difficult to reason about.</p><p>This article shows how TaskBase implements authorization using a generic RBAC engine and explicit, immutable policy definitions.</p><h3>Authentication Is Not Authorization</h3><p>Authentication answers:</p><p>Who are you?</p><p>Authorization answers:</p><p>What are you allowed to do?</p><p>These two concerns are fundamentally different.</p><p>In many Django projects, authorization logic ends up scattered across the codebase:</p><pre>if request.user == project.owner:</pre><p>or:</p><pre>if request.user in project.collaborators.all():</pre><p>This works initially.</p><p>But it tightly couples authorization logic to models and framework code.</p><p>Over time, the system becomes harder to maintain and harder to trust.</p><h3>Authorization Starts with Scope</h3><p>In TaskBase, authorization begins with a simple abstraction:</p><pre>@dataclass(frozen=True)<br>class Scope(Generic[RoleT]):<br>    role: Optional[RoleT]<br>    bypass: bool</pre><p>Scope represents the user’s authority within a specific resource.</p><p>It answers:</p><p>What role does this user have here?</p><p>The bypass flag grants full access. This is used for ownership.</p><p>Ownership becomes part of the authorization model — not a special case scattered across the codebase.</p><h3>The RBAC Engine</h3><p>Authorization rules are evaluated by a generic, framework-agnostic RBAC engine:</p><pre>@dataclass(frozen=True)<br>class RBACRules(Generic[RoleT]):<br>    read_roles: FrozenSet[RoleT]<br>    write_roles: FrozenSet[RoleT]<br>    manage_roles: FrozenSet[RoleT]<br>    delete_roles: FrozenSet[RoleT]<br>    <br>    def can_write(self, scope: Scope[RoleT]) -&gt; bool:<br>        return bool(<br>            scope.bypass or (scope.role is not None and scope.role in self.write_roles)<br>        )</pre><p>This engine:</p><p>does not know about Django<br>does not know about models<br>does not know about HTTP</p><p>It evaluates authorization logic only.</p><p>This makes it easy to test and easy to reason about.</p><h3>Policies Define the Permission Model</h3><p>Actual permission rules are defined using policy objects.</p><p>For example, project rules:</p><pre>PROJECT_RULES = RBACRules(<br>    read_roles=frozenset({<br>        CollaboratorRole.MAINTAINER,<br>        CollaboratorRole.DEVELOPER,<br>        CollaboratorRole.VIEWER,<br>    }),<br>    write_roles=frozenset({<br>        CollaboratorRole.MAINTAINER,<br>    }),<br>    manage_roles=frozenset({<br>        CollaboratorRole.MAINTAINER,<br>    }),<br>    delete_roles=frozenset(),  # owner-only via bypass<br>)</pre><p>Task rules:</p><pre>TASK_RULES = RBACRules(<br>    read_roles=frozenset({<br>        CollaboratorRole.MAINTAINER,<br>        CollaboratorRole.DEVELOPER,<br>        CollaboratorRole.VIEWER,<br>    }),<br>    write_roles=frozenset({<br>        CollaboratorRole.MAINTAINER,<br>        CollaboratorRole.DEVELOPER,<br>    }),<br>    manage_roles=frozenset(),<br>    delete_roles=frozenset({<br>        CollaboratorRole.MAINTAINER,<br>        CollaboratorRole.DEVELOPER,<br>    }),<br>)</pre><p>Policies use frozenset to ensure immutability and prevent accidental runtime modification.</p><p>This makes authorization rules explicit configuration.</p><p>Not a mutable application state.</p><h3>Django REST Framework Enforces — It Does Not Define</h3><p>Django REST Framework permission classes enforce rules:</p><pre>return TASK_RULES.can_write(scope)</pre><p>But they do not define them.</p><p>This keeps authorization logic inside the domain layer.</p><p>Not inside the framework.</p><h3>Ownership Is Handled Through Bypass</h3><p>Instead of writing special ownership checks everywhere:</p><pre>if user == project.owner:</pre><p>TaskBase evaluates:</p><pre>scope.bypass</pre><p>This keeps authorization logic consistent and predictable.</p><p>Ownership is not a special case.</p><p>It is part of the authorization model.</p><h3>Why This Structure Matters</h3><p>Authorization becomes:</p><p>Explicit<br>Predictable<br>Testable</p><p>Adding roles requires changing policies — not rewriting views.</p><p>Changing permission logic does not require touching serializers.</p><p>The system evolves by changing its configuration.</p><p>Not scattered conditionals.</p><h3>Authorization Should Be Boring</h3><p>Authorization should not be surprising.</p><p>It should be easy to understand.</p><p>Easy to change.</p><p>And easy to trust.</p><p>This requires treating authorization as a first-class architectural concern.</p><p>Not as scattered conditionals.</p><h3>What Comes Next</h3><p>In the next article, we’ll look at soft delete and data lifecycle management.</p><p>And why production systems rarely delete data permanently.</p><p>Full source code:</p><p><a href="https://github.com/imgeaslikok/taskbase-api">https://github.com/imgeaslikok/taskbase-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e61bc8e1c54d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/production-ready-django/authorization-is-architecture-implementing-rbac-in-django-e61bc8e1c54d">Authorization Is Architecture: Implementing RBAC in Django</a> was originally published in <a href="https://medium.com/production-ready-django">Production-Ready Django</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT Authentication in Django: The Production Way]]></title>
            <link>https://medium.com/production-ready-django/jwt-authentication-in-django-the-production-way-15714fcaa215?source=rss-ca11dd4e8233------2</link>
            <guid isPermaLink="false">https://medium.com/p/15714fcaa215</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Aslı Kök]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 09:59:04 GMT</pubDate>
            <atom:updated>2026-03-06T11:51:05.072Z</atom:updated>
            <content:encoded><![CDATA[<h4>How refresh rotation, token revocation, and throttling make JWT authentication production-ready</h4><p>Most JWT authentication examples stop at issuing tokens. Production systems cannot.</p><p>If your goal is a backend that is secure, maintainable, and scalable, you need to understand <strong>why</strong> and <strong>how</strong> authentication decisions affect your entire system.</p><p>In this article, we’ll look at JWT authentication in Django through the lens of real-world production concerns.</p><h3>Why JWT at All?</h3><p>JSON Web Tokens (JWT) are a stateless token format that allows your API to authenticate users without server-side session storage.</p><p>Benefits:</p><ul><li>stateless authentication</li><li>horizontal scalability</li><li>simple token introspection</li></ul><p>However, JWT has pitfalls.</p><p>A naive implementation can lead to:</p><ul><li>replay attacks</li><li>token misuse</li><li>poor logout experience</li></ul><p>That’s why production systems apply <strong>rotation and revocation</strong> patterns.</p><h3>Refresh Token Rotation</h3><p>A refresh token allows a client to obtain a new access token once the current access token expires.</p><p>But if you use refresh tokens forever, your system becomes vulnerable:</p><ul><li>old refresh tokens can be replayed</li><li>logouts don’t reliably work</li></ul><p>Solution: <strong>rotate refresh tokens</strong>.</p><p>With rotation:</p><ul><li>every refresh request yields a new refresh token</li><li>the old refresh token is invalidated</li></ul><p>In our Django setup, this is enabled in settings:</p><pre>SIMPLE_JWT = {<br>    &quot;ROTATE_REFRESH_TOKENS&quot;: True,<br>    &quot;BLACKLIST_AFTER_ROTATION&quot;: True,<br>}</pre><p>This makes refresh tokens more ephemeral and harder to misuse.</p><h3>How Logout Works in Stateless Systems</h3><p>JWT access tokens cannot be deleted server-side because they are stateless.</p><p>So, how do you implement logout?</p><p>You revoke the <strong>refresh token</strong>, not the access token.</p><p>This means:</p><ul><li>the client can no longer refresh a new access token</li><li>access tokens still expire normally</li></ul><p>Our logout endpoint simply blacklists the refresh token:</p><pre>RefreshToken(refresh).blacklist()</pre><p>This minimal approach preserves statelessness while giving clients a way to logout.</p><h3>Preventing Abuse with Scoped Throttling</h3><p>Login and refresh endpoints are particularly vulnerable to abuse:</p><ul><li>brute-force attempts</li><li>token replay attacks</li><li>dictionary attacks</li></ul><p>To mitigate this, we use DRF’s ScopedRateThrottle:</p><pre>throttle_classes = [ScopedRateThrottle]<br>throttle_scope = &quot;auth_login&quot;</pre><p>and assign separate scopes for login and refresh.</p><p>This gives you:</p><ul><li>separate rate limits</li><li>clear guardrails for abuse patterns</li></ul><h3>Common Pitfalls and How We Avoid Them</h3><h3>❌ Accepting expired tokens silently</h3><p>Never do it. Always return 400 on invalid/expired tokens.</p><h3>❌ Keeping refresh tokens forever</h3><p>Rotate and blacklist to reduce attack surface.</p><h3>❌ Mixing session auth and JWT indiscriminately</h3><p>Keep your API auth consistent.</p><h3>Summary</h3><p>JWT isn’t magic — it’s a tool.</p><p>Use it well by:</p><ul><li>rotating refresh tokens</li><li>blacklisting revoked tokens</li><li>applying rate limits</li><li>keeping the API contract clear</li></ul><p>In the next article, we’ll talk about <strong>Role-Based Access Control</strong> and how it’s implemented in TaskBase with a rules engine.</p><p>Check out the source code at:</p><p><a href="https://github.com/imgeaslikok/taskbase-api">https://github.com/imgeaslikok/taskbase-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15714fcaa215" width="1" height="1" alt=""><hr><p><a href="https://medium.com/production-ready-django/jwt-authentication-in-django-the-production-way-15714fcaa215">JWT Authentication in Django: The Production Way</a> was originally published in <a href="https://medium.com/production-ready-django">Production-Ready Django</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Structure Matters More Than You Think in Django]]></title>
            <link>https://medium.com/production-ready-django/project-structure-matters-more-than-you-think-in-django-bc559b3c0824?source=rss-ca11dd4e8233------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc559b3c0824</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Aslı Kök]]></dc:creator>
            <pubDate>Sat, 28 Feb 2026 09:52:04 GMT</pubDate>
            <atom:updated>2026-03-06T11:50:44.601Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to structure Django projects for long-term maintainability</h4><p>Most Django tutorials start the same way.</p><p>Create a project.<br>Create an app.<br>Add models.<br>Add views.</p><p>Until it doesn’t.</p><p>Not because Django is bad, but because the default structure stops helping once the project grows beyond a certain size.</p><p>This article explains how I structure Django projects when building real systems — and why structure is one of the most important decisions you make early.</p><h3>The Default Structure Works — Until It Doesn’t</h3><p>A typical Django project looks like this:</p><pre>project/<br>  project/<br>    settings.py<br>    urls.py</pre><pre>  app1/<br>  app2/</pre><p>This works fine in small projects.</p><p>But over time, problems appear:</p><ul><li>domain logic spreads across multiple apps</li><li>API code mixes with business logic</li><li>permissions, serializers, and queries become tightly coupled</li><li>changes become harder to reason about</li></ul><p>The issue is not Django itself.</p><p>The issue is a lack of clear architectural boundaries.</p><h3>The Principle: Structure by Domain, Not by Framework</h3><p>Instead of organizing code around Django concepts, I organize it around business domains.</p><p>In TaskBase, the structure looks like this:</p><pre>apps/<br>  users/<br>  projects/<br>  tasks/</pre><pre>api/<br>  v1/</pre><pre>config/</pre><p>Each part has a clear responsibility.</p><ul><li>apps/ contains domain logic</li><li>api/ exposes the domain via HTTP</li><li>config/ contains infrastructure and settings</li></ul><p>This separation makes the system easier to evolve.</p><h3>Django Is the Adapter, Not the Core</h3><p>One of the most important mindset shifts is this:</p><p>Django is not your system.</p><p>It is the interface to your system.</p><p>The real system lives in your domain.</p><p>This means:</p><ul><li>business rules belong in apps/</li><li>API concerns belong in api/</li><li>configuration belongs in config/</li></ul><p>This prevents your domain from becoming tightly coupled to the framework.</p><p>And that matters more than it seems.</p><p>Because frameworks change.<br>Your domain logic should not need to.</p><h3>Why This Matters in Practice</h3><p>This structure enables several important capabilities later:</p><p>You can:</p><ul><li>change API versions without touching domain logic</li><li>add background workers without rewriting business rules</li><li>test domain logic independently</li><li>reason about permissions and data access clearly</li></ul><p>It reduces friction as the system grows.</p><p>Not by adding complexity.</p><p>But by placing complexity in the right place.</p><h3>This Is Still a Monolith — and That’s Good</h3><p>TaskBase is not a microservice system.</p><p>It is a modular monolith.</p><p>And that is intentional.</p><p>Microservices solve scaling problems.</p><p>They also introduce operational complexity.</p><p>Most systems do not need that early.</p><p>A well-structured monolith can scale much further than people expect.</p><h3>Minimal Does Not Mean Naive</h3><p>TaskBase is intentionally minimal.</p><p>But it demonstrates several production-grade architectural decisions:</p><ul><li>domain-based structure</li><li>API versioning</li><li>authentication and authorization boundaries</li><li>query optimization patterns</li><li>observability primitives</li></ul><p>Not because complexity is required.</p><p>But because clarity is.</p><h3>What Comes Next</h3><p>In the next article, I’ll explain how authentication is implemented in TaskBase using JWT — and the production decisions behind it.</p><p>Including:</p><ul><li>why refresh token rotation matters</li><li>how logout works in stateless systems</li><li>and how to avoid common mistakes</li></ul><h3>Final Thoughts</h3><p>Project structure is not just organization.</p><p>It is architecture.</p><p>And architecture determines how your system behaves under change.</p><p>Getting it right early does not make your project bigger.</p><p>It makes it easier to grow.</p><p>If you’re interested, the full source code is available here:</p><p><a href="https://github.com/imgeaslikok/taskbase-api">https://github.com/imgeaslikok/taskbase-api</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc559b3c0824" width="1" height="1" alt=""><hr><p><a href="https://medium.com/production-ready-django/project-structure-matters-more-than-you-think-in-django-bc559b3c0824">Project Structure Matters More Than You Think in Django</a> was originally published in <a href="https://medium.com/production-ready-django">Production-Ready Django</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring Concurrency Safety in Django: Preventing Race Conditions in Data-Critical Applications]]></title>
            <link>https://medium.com/@imgeaslikok/ensuring-concurrency-safety-in-django-preventing-race-conditions-in-data-critical-applications-d631e6be58da?source=rss-ca11dd4e8233------2</link>
            <guid isPermaLink="false">https://medium.com/p/d631e6be58da</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-engineering-team]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[Aslı Kök]]></dc:creator>
            <pubDate>Mon, 23 Feb 2026 15:52:35 GMT</pubDate>
            <atom:updated>2026-02-23T15:57:25.735Z</atom:updated>
            <content:encoded><![CDATA[<p>Concurrency control is a fundamental requirement in any data-critical backend system. Applications that manage financial transactions, inventory, reservations, or shared counters must ensure that concurrent operations do not compromise data integrity.</p><p>Although Django provides a robust ORM and transaction support, it does not automatically prevent race conditions. Without explicit concurrency control, applications remain vulnerable to subtle and potentially severe data consistency issues.</p><p>This article explains the nature of race conditions in Django, reviews standard mitigation techniques, and introduces a reusable approach designed to simplify concurrency-safe updates using a decorator-based abstraction.</p><h3>Understanding the Race Condition Problem</h3><p>Consider a simplified account model:</p><pre>class Account(models.Model):<br>    balance = models.IntegerField()</pre><p>And a withdrawal operation:</p><pre>def withdraw(account, amount):<br>    if account.balance &gt;= amount:<br>        account.balance -= amount<br>        account.save()</pre><p>Under concurrent access, multiple processes may read the same balance value before either update is committed.</p><p>Example scenario:</p><p>Initial balance: 100<br>Two concurrent withdrawals: 80 and 80</p><p>Both operations read: balance = 100<br>Both subtract 80<br>Both save</p><p>Final balance becomes: 20</p><p>This violates data consistency expectations and demonstrates a classic race condition resulting in lost updates.</p><h3>Why Django Does Not Prevent This by Default</h3><p>Django’s ORM operates under the database isolation level configured by the database, typically <strong>READ COMMITTED</strong>.</p><p>In this mode:</p><ul><li>Reads do not lock rows</li><li>Concurrent writes can overwrite each other</li><li>Consistency guarantees must be enforced at the application level when required</li></ul><p>Therefore, concurrency safety must be implemented explicitly.</p><h3>Standard Concurrency Control Techniques</h3><h4>Pessimistic Locking with select_for_update</h4><p>Django provides row-level locking:</p><pre>Account.objects.select_for_update().get(id=account_id)</pre><p>Advantages:</p><ul><li>Strong consistency guarantees</li><li>Prevents concurrent modification</li></ul><p>Disadvantages:</p><ul><li>Requires explicit transaction management</li><li>Adds repetitive boilerplate</li><li>Easy to forget in complex systems</li></ul><h4>Optimistic Locking</h4><p>Uses a version field:</p><pre>version = models.IntegerField()</pre><p>Advantages:</p><ul><li>High performance under low contention</li><li>Non-blocking</li></ul><p>Disadvantages:</p><ul><li>Requires additional implementation logic</li><li>Retry handling increases complexity</li></ul><h3>Limitations of Ad-Hoc Implementations</h3><p>While effective, implementing concurrency protection manually introduces problems:</p><ul><li>Code duplication</li><li>Increased risk of incorrect usage</li><li>Reduced maintainability</li><li>Inconsistent protection across the codebase</li></ul><p>A reusable abstraction improves reliability and consistency.</p><h3>A Reusable Approach: django-concurrency-safe</h3><p>To address this need, I developed a reusable library that simplifies concurrency-safe operations in Django using a decorator-based approach.</p><p>Repository:</p><p><a href="https://github.com/imgeaslikok/django-concurrency-safe">https://github.com/imgeaslikok/django-concurrency-safe</a></p><p>The goal is to make concurrency safety explicit, reusable, and easy to apply.</p><h3>Example Usage with Decorator</h3><p>Using the library, concurrency protection can be applied directly to business logic:</p><pre>from concurrency_safe import concurrency_safe</pre><pre>@concurrency_safe()<br>def withdraw(account_id: int, amount: int):</pre><pre>    account = Account.objects.get(id=account_id)</pre><pre>    if account.balance &lt; amount:<br>        raise ValueError(&quot;Insufficient balance&quot;)</pre><pre>    account.balance -= amount<br>    account.save()</pre><p>The decorator ensures that concurrent executions of this function do not result in lost updates or inconsistent state.</p><p>This removes the need to manually write locking logic for every critical operation.</p><h3>Equivalent Manual Implementation</h3><p>Without a reusable abstraction, the same logic requires explicit locking:</p><pre>from django.db import transaction</pre><pre>def withdraw(account_id, amount):</pre><pre>    with transaction.atomic():</pre><pre>        account = (<br>            Account.objects<br>            .select_for_update()<br>            .get(id=account_id)<br>        )</pre><pre>        if account.balance &lt; amount:<br>            raise ValueError()</pre><pre>        account.balance -= amount<br>        account.save()</pre><p>This approach works, but introduces repetitive boilerplate and increases the risk of inconsistent usage.</p><h3>Why a Decorator-Based Approach Improves Reliability</h3><p>The decorator provides:</p><ul><li>Explicit concurrency protection at the function level</li><li>Reduced boilerplate</li><li>Consistent application across the codebase</li><li>Improved maintainability</li><li>Lower risk of developer error</li></ul><p>Concurrency safety becomes part of the function definition rather than an implicit implementation detail.</p><h3>Internal Behavior (High-Level Overview)</h3><p>Internally, the decorator wraps the function execution within a controlled database transaction and applies appropriate locking mechanisms to prevent concurrent modification of the same data.</p><p>This ensures safe updates while keeping business logic clean and readable.</p><h3>When Concurrency Safety Is Essential</h3><p>Explicit concurrency control is critical in systems involving:</p><ul><li>Financial balances and wallets</li><li>Inventory management</li><li>Reservation and booking systems</li><li>Counters and quotas</li><li>Any shared mutable state</li></ul><p>Ignoring concurrency risks can lead to irreversible data corruption.</p><h3>Key Takeaways</h3><p>Django does not automatically prevent race conditions</p><p>Concurrent updates can silently corrupt data</p><p>Manual locking works, but introduces complexity</p><p>Reusable abstractions improve reliability and maintainability</p><p>Decorator-based concurrency protection simplifies implementation</p><h3>Conclusion</h3><p>Concurrency safety is a critical responsibility in backend engineering. While Django provides the necessary tools, proper implementation depends on application design.</p><p>Reusable abstractions can significantly reduce the risk of data corruption and improve system reliability.</p><p>As systems scale and concurrency increases, explicit concurrency control becomes essential for maintaining data integrity.</p><h3>References</h3><p>Project repository:</p><p><a href="https://github.com/imgeaslikok/django-concurrency-safe">https://github.com/imgeaslikok/django-concurrency-safe</a></p><h3>If you found this useful</h3><p>If this article was helpful, consider:</p><p>⭐ Starring the GitHub repository<br>🔁 Sharing the article<br>💬 Providing feedback</p><h3>Author</h3><p>Backend Engineer with 5+ years of experience building Django-based systems. Focused on concurrency safety, system reliability, and designing data-critical backend architectures.</p><p>GitHub: <a href="https://github.com/imgeaslikok">https://github.com/imgeaslikok</a><br>LinkedIn: <a href="https://linkedin.com/in/aslikok">https://linkedin.com/in/aslikok</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d631e6be58da" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>