Part 5: Enhancements and Architecture Decisions
Enhancing Database Read Latency via Batch Fetching
This is a way to avoid the N+1 query problem, and also avoid the duplication for rows that have many related rows in the other table that happens in join.
The batch-loading is simply fetching all of the related data in one query with the collected IDs. For example, we first fetch all board columns, then fetch their tasks in another query using WHERE column_id IN (col_id_1, col_id_2, ...).
I decided to use it and it sends just 3 queries for the full board details including columns in each board and tasks in each column.
Offloading Database Reads and Reducing Latency via Caching
I found out that different caching strategies don't automatically eliminate consistency issues under concurrent operations, especially under the default rule for concurrent systems: Start order does not guarantee completion order. Race conditions can still cause stale data be written into cache.
I decided to use the cache-aside strategy because of its simplicity: reads populate the cache on misses, while writes update the database and invalidate the affected cache entries.
Race Condition in Cache-Aside Technique
Suppose board:1 isn't cached yet, and its title in the database is "Old". User X opens the board. Because the cache is empty, request will query the database and get board name "Old", then writes to cache.
Before the retrieved value is cached (before user x's request is finished), user Y renames the board to "New" then commits the change to the database and deletes board:1 entry from Redis to invalidate the cache, but since the key doesn't exist, nothing happens.
User X's slow read request finally finishes and writes the stale value "Old" into Redis. Redis now holds "Old" and DB holds "New". Every later reader gets "Old". Nothing will fix it.
This is where the TTL provides an important safety net. The stale value will eventually expire, causing a cache miss and forcing the next reader to fetch the current value from the database. Therefore, when this race condition occurs, the TTL bounds the maximum time the stale value can remain in the cache. It doesn't prevent the race condition, yet limits its impact.
Deciding What to Cache
Any request to read board details happens in 2 steps, the first is querying to the user-board roles table to check that the user is a member for this board, and the second is retrieving the board data.
This could be solved via caching, I decided to cache boards data as it is 3 database queries the first for board and the second for its columns and the third for tasks per each column, so it would be faster when cached. Also I decided to keep 5-minute TTL for each board.
Also it is a good idea to cache user roles on boards as it is required in every action on the board or its columns or its tasks. Caching the roles trades security for speed: a failed delete or race condition (explained above) can leave a stale role, so a user keeps old privileges from the cache until the TTL expires.
But database server can use RAM for faster retrieval, why to use Redis? Without caching in memory (RAM), the database server would rerun the work on every request (parse, plan, join and executes, then retrieve then the mapping of ORM to an object) even it will read it from RAM instead of hard disk. A Redis hit skips all of that, because it returns the finished JSON. So RAM utilizing in database server removes the disk cost but not the compute cost.
The Load Testing Profile and Enhancement
I started with a simple baseline test that sent requests with random board IDs. It was useful as a quick sanity check, but it had several flaws that I addressed in my second testing profile:
- Saturated, closed-loop load (fixed): Both sets ran at the server's ceiling, so latencies were mostly queueing time on one worker rather than single-request cost. The 6.5x P95 gain mixed "faster per request" with "less queueing," overstating what a single user would feel. In the updated profile, I moved away from a saturated ceiling test to better isolate request behavior.
- Easy, uniform workload (fixed): The baseline was read-only with uniform access over 50 boards, giving a near-perfect hit ratio without testing invalidation or hot keys. In the new profile, I added a mixed read/write workload (to exercise cache invalidation) and skewed board reads so some boards get heavier traffic than others, mimicking real-world access patterns.
- Runs shorter than the TTL (fixed): At 20s per run against a 300s TTL, expirations and stampedes were rare, and the "after" set mixed cold and warm runs. In the updated profile, I adjusted the TTL and run duration so boards actually expire during the test.
- Weak correctness checks: The only check was HTTP 200, meaning a stale cached board would still pass. With mixed read/write traffic, skewed reads, and real expirations in place, the second profile gave me a much more realistic picture of caching and invalidation behavior.
Results of Caching
Cache Hit:
keyspace_hits: 2339keyspace_misses: 710- cache-hit ratio: ~75%
P99 Latency Across All Runs
Baseline Runs (Without Caching)
- Run 1: 558.53ms
- Run 2: 935.97ms
- Run 3: 647.41ms
- Average: 713.97ms
Cached Runs (With Caching)
Run 1: 163.51ms
Run 2: 112.28ms
Run 3: 133.20ms
Average: 136.33ms
Absolute Reduction: Dropped by 577.64ms
Percentage Improvement: 80.9% faster
Throughput
The throughput (number of handled requests per second) did not change, as the test runs with a moderate load that the server could withstand and handle without being stressed. Caching here allowed the system to serve these requests 80% faster at P99 with significantly less DB strain rather than pushing higher req/s, if the load was high and the server is saturated, then there would be improvement in the throughput as the server can serve/process more requests.
For detailed k6 load testing results, take a look on the GitHub Repo tests folder: mazenaly256 / Kanban-Flow Real-time collaborative project management web application with Kanban-style boards
The Problem in Inline Side Effects
I identified a problem that is the task write endpoint was orchestrating everything:
- Commit to Postgres (the source of truth).
- Delete the Redis cache key.
- Broadcast over WS.
With this inline synchronous setup, the endpoint knows about every downstream system (tight coupling) and waits for each side effect to finish successfully before executing the next one. Steps 2 and 3 canβt be retried, because they sit outside the transaction (lacks atomicity), so any of them can fail or be skipped after a successful database commit, so the change is made but its side effects are not executed.
Furthermore, the user dealing with tasks needs to wait for the endpoint to finish caching-related work and WebSockets broadcasting, and any fail happened to one of them will make the endpoint fails, even the operation on task has been done successfully on database.
Also there is dual-write problem. Executing the side effects are additional operations next to the database change inside the endpoint. If the endpoint commits and then invalidates the cache and then publishes to the board clients via WebSockets, a crash in between saves the task to the database but loses its side effects.
The Solution: Transactional Outbox Pattern
The Outbox pattern fixes it: the endpoint writes the resource change and data required to execute side effects in a single row (in an outbox table) in the same transaction on database, so the side effects and outbox row exists if and only if the change also exists.
A separate relay (background job that continuously polls the outbox table and perform a job like executing the side effects or publishing to the stream) reads unpublished outbox rows and performs the changes on the other systems. If the relay crashes, the rows stay in the table and side effects are executed by the relay after restart.
Delivery of the side effect is therefore at-least-once: if the relay processed/executed the side effect and crashes before marking the row as published, it executes the same side effect again after restart. Consumers must tolerate duplicates (should be idempotent) as the same side effect can be executed more than once.
Enhancement on Outbox Table: Partial Indexing
The outbox table contains partial index on pending rows, for faster retrieval, considering only the pending side outbox rows, introducing some benefits:
- Smaller index: Processed events don't occupy index space (Space efficiency).
- Faster queries: The database searches a smaller index when retrieving pending events.
- Lower write overhead: Changes to rows that don't satisfy the predicate don't require maintaining entries in this index.
- Better cache efficiency: A smaller index is more likely to fit in memory so Postgres can cache it for faster retrieval.
Both full and partial indexes support the pending-events query, but the partial index avoids storing entries for the processed events. The database can use the partial index directly to locate pending events without bothering for processed events (limiting the search space hence reducing the latency).
The Outbox is about correctness: after a crash, no DB-saved write loses its side effects (which is publishing an event to the stream in event-driven architecture). Simply: one extra INSERT in the transaction, and all side effects leave the endpoint.
The Impact
The P95 latency reduced by about 13%, it is not a big percentage but remember that I have only two light side effects which are broadcasting and cache invalidation, in more complicated system these side effects may be much larger and take more time.
I recorded ZERO lost side effects while achieving the decoupling between the request and side effects failure or latency. The relay automatically processed/delivered 121 pending side effects from injected 60-second Redis outage/failure, in around 1.5 seconds from recovery. Before outbox, the request was staying 4 seconds when the Redis is down, and then it fails though the operation is done successfully and the issue is only in the side effect.
Some Trade-offs: Delivery of the side effect is now eventual, there is a delay by 100ms (the relay sleeping time between polls) also more computations like fetching the outbox rows and loop on them.
Ensuring "Freshness over liveness": the relay deletes the cache key before broadcasting, so a client that refetches after a message never reads a stale cached board (the broadcast waits for the cache delete). The cost of this is liveness: while Redis is down no broadcasts go out, so other users donβt see updates live, though a manual refetch still reads from the database (as fetching from cache is skipped as the caching server is down). Separately, one failing row blocks the rows behind it (head-of-line blocking).
Event-Driven Architecture (Asynchronous Communication via Messaging)
Why Outbox is Not Enough? Whatβs still wrong after the outbox: one relay runs both side effects in sequence. A stuck row blocks every row behind it, the row can be stuck as the cache invalidation and the broadcast canβt fail or retry separately, also without EDA and a third reaction (notifications) means modifying the relay logic. Simply, we decoupled the request path from side effects, but the consumers are still tightly coupled.
Solution With events, the endpoint records that something happened (e.g. task_updated) which means publishing the event and then the API responds to the user, without performing any inline side effects inside the endpoint. Two independent consumers react to this event: Cache consumer: invalidates the key. Broadcast consumer: pushes to board subscribers.
So there is a stream with multiple consumer groups, every consumer group for a single side effect, so there is a group for WebSocket broadcasting and another one for cache invalidation. The request is faster, because it no longer waits. It is also safer, because a slow or failing side effect canβt fail a request whose task operation is already processed successfully.
Trade-off: The side effects now happen after the response, so the system is eventually consistent: a user who saves a task and immediately refetches may read stale cached data until the cache consumer runs. There is also a dual-write problem that is writing the change to database and publishing the event to the broker, so we still need transactional outbox pattern here also, that commits the task write and the event in one row combining the database change with the publishing for the event in one atomic transaction. The relay here should just publish the message to the stream instead of doing the side effects directly.
The value here is the design, with no big number or optimization. The core benefit is that a failing consumer no longer blocks the other (in the outbox-only relay, one stuck row blocked both), and a message that is unacknowledged is retried (even if it is done, this is at-least-once delivery).
Complete Event-Driven Pipeline for Task Write
When any task write happens there is a flow of operations happens regarding this event:
The edit and its outbox record goes to database in a single transaction (atomicity). The relay takes these undelivered records, and adds to a specific stream (that is append-only log, and can be trimmed) called task:events, and each message in the stream get a message_id. Then the relay marks the outbox record as published only after adding to the stream successfully, so this is the first layer of at-least-once delivery.
The cache and WebSocket broadcasting consumer groups independently read undelivered messages from the task:events stream. When Redis delivers a message to a group, it records the message ID in that group's Pending Entries List (PEL) until the consumer explicitly acknowledges it (XACK).
Because my consumer
Comments
No comments yet. Start the discussion.