Write Buffering, Batching, Coalescing, Sharded Counters & Data Locality
"Write throughput increases linearly with the number of shards, so a distributed counter with 10 shards can handle 10x as many writes as a traditional counter." — Firebase documentation, Distributed counters (Cloud Firestore solutions)
Summary: A database that is asked to do one small durable write per event spends its time on round trips, commits and row locks instead of on data; the fix is to take writes off the hot path (buffer), send them together (batch), merge the ones that say the same thing (coalesce), split the one row everybody fights over (shard), and keep related data together so one write touches one place (locality). Focus: write buffering and the durability window, acknowledgement semantics and crash loss, batching (size versus latency, COPY, multi-row INSERT, ON CONFLICT upserts, Kafka linger.ms and batch.size, Redis pipelining), coalescing (deltas versus last-writer-wins, write-behind), sharded counters (hot row, sub-counters, sum on read, INCRBY, Firestore-style counters), approximate counters and HyperLogLog, bounded staleness, idempotent batches and dedup keys, per-key ordering, data locality, hot partitions and key salting, time-series write patterns, with Go and Laravel 13 code. Learning goal: For any write-heavy path (view counter, like counter, analytics ingest, import job), choose the combination of buffer, batch, coalesce and shard that meets a stated durability and staleness contract, write it so a crash or a retry cannot corrupt the numbers, and size it with real arithmetic.
This chapter sits in the Traffic & Scale group, after Caching (which owns write-behind as a cache policy; here it is the buffering view of the same idea) and before CAP & PACELC. It owns the system-level decision and the numbers. Mechanics live with the owners: WAL, fsync and crash recovery in Durability, WAL & Crash Recovery, row locks in Locks & Concurrency Control, LSM write paths in Storage Engines, HyperLogLog and Bloom filters in Bloom Filters & Probabilistic Structures, consistent hashing in Consistent Hashing, shard-key choice in Sharding at System Level, delivery guarantees and per-partition ordering in Delivery Guarantees and Ordering, and request-level idempotency in API Idempotency.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why one write per event does not scale | Why it exists |
| Sources: PostgreSQL, Redis, Kafka, Firestore, DynamoDB | Where it comes from |
| Keeping writes in memory or a queue before the database | Write buffering, Durability window |
| Size versus latency, COPY, multi-row INSERT, pipelining | Batching |
| Collapsing many updates into one | Coalescing, Write-behind |
| One row everybody updates | Sharded counters |
| Approximate and distinct counts | Approximate counters and HyperLogLog |
| How stale is allowed | Bounded staleness |
| Retries and duplicate batches | Idempotent batch writes |
| Order inside a batch | Ordering |
| Keeping related data together | Data locality, Cache locality |
| One celebrity key | Hot partitions and key salting |
| Metrics and events over time | Time-series writes |
| Knobs, limits and error messages | Mechanics |
| Code | Go, Laravel |
| View counter, like counter, analytics ingest, imports | Solving the classic problems |
| Which technique for which workload | Choosing |
| Monolith to distributed system | In architecture |
| Numbers and failure drills | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The five moves.
| Move | In plain words | Tiny example | What it buys | What it costs |
|---|---|---|---|---|
| Buffer | Hold the write somewhere cheap and acknowledge now | Append the event to an in-memory queue or a Redis list | Low latency, absorbs spikes | A window where data exists only in the buffer |
| Batch | Send many writes in one round trip | One multi-row INSERT, one COPY, one Redis pipeline | Fewer round trips, commits and syscalls | Added latency up to the flush interval |
| Coalesce | Merge writes to the same key before sending | 1,000 views + 1 become one views + 1000 | Fewer rows touched, less lock time | Intermediate values are never visible |
| Shard | Split one hot key into N sub-keys | Counter row becomes 16 rows, pick one at random | Write throughput grows with N | Reads must sum N values |
| Co-locate | Put data that is used together in one place | Partition by user_id so one user's rows share a shard | One write or query touches one node | Skew when one key is huge |
The contracts you must state. Every one of these techniques trades something for throughput; the trade is only safe when it is written down.
| Contract | The question | Typical answer for a view counter | Typical answer for a payment |
|---|---|---|---|
| Durability window | How much acknowledged data may a crash lose? | Up to the last flush (seconds) | None: write-ahead, then acknowledge |
| Staleness bound | How old may a read be? | Flush interval plus replica lag | Read your own write |
| Accuracy | Must the number be exact? | Approximate is fine for display; exact in the ledger | Exact |
| Ordering | Which order must be preserved? | None, increments commute | Per account, strictly |
| Duplicates | What if a batch is applied twice? | Dedup key or absolute values | Idempotency key mandatory |
Numbers to keep in your head. All are either from the cited documentation or marked as a back-of-envelope estimate.
| Fact | Value | Source |
|---|---|---|
| Redis round trip over a slow Internet link | 250 ms RTT caps one client at 4 requests per second, whatever the server can do | Redis pipelining docs |
| Redis pipeline batch the docs suggest | Around 10,000 commands, then read replies | Redis pipelining docs |
| Kafka producer defaults | linger.ms 5 (since Kafka 4.0, it was 0), batch.size 16384 bytes | Kafka ProducerConfig |
| PostgreSQL asynchronous commit risk window | At most three times wal_writer_delay | PostgreSQL docs, section 28.4 |
| Firestore counter shard | One sustained increment per second per shard document; 10 shards give 10x | Firebase docs |
| DynamoDB single partition ceiling | 3,000 RCU and 1,000 WCU for one item key | DynamoDB docs |
| Single hot row (estimate, not a measurement) | If the row lock is held 1 ms, about 1,000 updates per second per row | Back-of-envelope |
| HyperLogLog in Redis | Up to 12 KB, standard error 0.81% | Redis docs |
The picture is the whole chapter in one line: writers return as soon as the item is in a bounded in-memory queue; a single flusher writes a batch when it is full or when the linger timer fires. Everything inside the amber box is the crash-loss window.
Why it exists
A database commit is an expensive event. A client sends a statement, the server parses it, takes locks, writes the change to the write-ahead log, waits for the log to reach stable storage, and answers. Do that once per page view and the cost per event is dominated by the network round trip and the log flush, not by the 16 bytes you changed. Redis documents the arithmetic for its own protocol: with a 250 ms round trip "even if the server is able to process 100k requests per second, we'll be able to process at max four requests per second". A second cost hides behind the first: when thousands of events all update the same row (a total, a like count, a stock level), each update waits for the row lock of the previous one, so the row becomes a single-lane road no matter how many servers you add.
| Without these techniques | With them |
|---|---|
| One round trip and one commit per event | One round trip and one commit per batch |
| N updates to one key take N lock turns | One update with the sum, or N shards in parallel |
| A traffic spike goes straight to the database | The spike lands in a buffer and drains at the database's pace |
| Hot keys cap total throughput | Hot keys spread over many rows or partitions |
| Latency follows the slowest commit | Latency follows an in-memory append |
| Simple, exact, durable at the moment of the response | Fast and cheap, but with a stated loss and staleness window |
One analogy, reused through the page: the mail room. Imagine a mailman who drives to the post office for every single letter (no buffer, no batch). Now give the street a mailbox: letters are dropped in and the person walking away is done (buffer), a van collects the box every hour or when it is full (batch with size or time flush), and ten letters for the same house are tied with one rubber band (coalesce). If the box burns before the van comes, those letters are gone (crash loss window). If one house gets a million letters, give it ten mailboxes (shards) and the postman adds them up at the end. If you deliver by street instead of by random order, the van takes one trip per street (locality).
Three common misunderstandings, up front
- "A bigger batch is always faster." Throughput rises with batch size only until the fixed cost is amortised; after that you only add latency, memory and the size of what a single failure can roll back. Kafka's own documentation says a small
batch.size"may reduce throughput" and that the maximum linger "gives the upper bound on the delay for batching". - "If I buffer, I lose data." You lose data only if you acknowledge before the data is durable and the buffer dies. A buffer that is itself durable (Kafka, a database table, a Redis list with
appendfsync always) moves the window; it does not remove the need to decide where it is. - "Sharding a counter makes it inexact." A sharded counter is exact once every increment has landed; what changes is that a read is a sum of N reads, not one atomic snapshot. The inexactness people fear comes from sampling and probabilistic structures, which are a separate, optional choice.
Where it comes from
Nothing in this chapter is new; each technique was written down by the vendor whose product needed it. This table lists what each source states, read from the saved pages (see References).
| Source | What it states | Why it matters here |
|---|---|---|
| PostgreSQL docs, 14.4 Populating a Database | "Use COPY to load all the rows in one command, instead of using a series of INSERT commands. The COPY command is optimized for loading large numbers of rows" | Batching bulk loads is a documented first-line tuning step |
| PostgreSQL docs, 28.4 Asynchronous Commit | "Asynchronous commit is an option that allows transactions to complete more quickly, at the cost that the most recent transactions may be lost if the database should crash." | The database's own durability-for-latency trade, with a bounded window |
PostgreSQL docs, INSERT | "ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome" and a cardinality violation if one command affects a row twice | The primitive under idempotent batch upserts and why a batch must be deduplicated |
| Redis docs, Pipelining | The 250 ms RTT arithmetic, and "send them as batches each containing a reasonable number, for instance 10k commands" | Client-side batching and why unbounded pipelines use server memory |
Kafka ProducerConfig | linger.ms "can be thought of as analogous to Nagle's algorithm in TCP"; default changed from 0 to 5 in Kafka 4.0 | Size-or-time flushing is the standard producer design |
| Firebase docs, Distributed counters | A counter is a document with a subcollection of shards "and the value of the counter is the sum of the value of the shards" | The canonical managed-service version of a sharded counter |
| DynamoDB developer guide, write sharding | "You can add a random number to the partition key values to distribute the items among partitions." | Key salting for hot partitions |
| DynamoDB, burst and adaptive capacity | A single item key can reach at most 3,000 RCUs and 1,000 WCUs of one partition | Why salting is still needed after adaptive capacity |
| Kleppmann, Designing Data-Intensive Applications (author's page) | The page describes a book that compares the trade-offs and fundamental limits of data systems; its partitioning chapter is the standard reading on skew and hot spots | The conceptual home of locality and hot partitions; not quoted here |
Every quotation in the table was read on the saved page. The DDIA row is a pointer to a book, not a quotation, and the page I read does not list chapter contents.
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, how products provide it, and the fix.
Write buffering Must-know
In plain words: accept the write into something fast and cheap (memory, a queue, a Redis list) and write it to the real database a moment later, in the background.
Common misunderstanding: "A queue in front of the database makes writes faster." It makes the caller faster. Total database work is the same unless you also batch or coalesce; if the buffer is faster at accepting than the database is at draining, it only grows until it fills or runs out of memory.
Definition: write buffering decouples the acknowledgement of a write from its application to the system of record. Throughput is protected by a bounded buffer and a drain rate; durability depends on where the buffer lives.
Client Buffer (bounded queue) Flusher Database
1 POST /view
2 -> append event queue depth 1 of 4096
3 <- 204 (acknowledged)
4 (more events arrive) depth 380 of 4096
5 linger timer fires
6 -> one multi-row INSERT commit
7 <- OK durable
8 buffer depth back to 0Real scenario: page-view and click tracking; IoT telemetry; audit trails that may lag a few seconds; chat "last seen" updates; imports where a user uploads a million rows.
Where the buffer can live:
| Buffer location | Survives process crash | Survives machine loss | Shared by many app servers | Typical use |
|---|---|---|---|---|
| In-process memory (channel, array) | No | No | No | Cheap metrics, best-effort events |
| Local disk spool (file, SQLite) | Yes | No | No | Agents and edge collectors |
| Redis list or stream (default persistence) | Depends on appendonly and appendfsync | With replication, mostly | Yes | Counters, small event streams |
Kafka topic (acks=all, replicated) | Yes | Yes | Yes | Analytics ingest, event backbone |
| Database queue table | Yes | As durable as the database | Yes | When the database is already the bottleneck-free part |
Fix / how to use it: choose the buffer from the durability contract (Durability window), bound it, decide what happens when it is full (block, shed, or spill), and drain it on shutdown. The Go batcher below shows all four.
Durability window, acknowledgement semantics and crash loss Must-know
In plain words: between the moment you tell the client "done" and the moment the data is safe on stable storage, a crash erases it. The length of that gap is the durability window.
Common misunderstanding: "The database is durable, so my buffered write is durable." Durability belongs to the component that acknowledged. If your application acknowledges when the item reaches its own memory, the database's guarantees do not apply to it yet.
Definition: the durability window is the period during which an acknowledged write exists only in volatile or unreplicated state. PostgreSQL gives it a name and a bound: with asynchronous commit the risk window is limited by the WAL writer, "three times wal_writer_delay".
Strategy A: ack after buffer Strategy B: ack after durable write
1 receive event receive event
2 append to memory queue write to WAL / Kafka acks=all
3 ack to client <-- window opens
4 ...50 ms later... ack to client (no window)
5 crash crash
6 event lost, client believes it saved event recovered on restartReal scenario: a like button where losing the last two seconds of likes after a crash is harmless; a payment event where it is not; an audit log where regulators say it is not.
What provides each acknowledgement level:
| Product | Setting | What "acknowledged" means | Loss on crash |
|---|---|---|---|
| PostgreSQL | synchronous_commit = on (default) | WAL flushed to disk before the answer | None for committed transactions |
| PostgreSQL | synchronous_commit = off | Answer before the WAL flush; WAL writer flushes in the background | Up to about three times wal_writer_delay; the database stays consistent |
| Kafka producer | acks=0 | Not waited for | Possible without notice |
| Kafka producer | acks=1 | Partition leader has appended | Lost if the leader dies before replication |
| Kafka producer | acks=all | All in-sync replicas have appended | None while min.insync.replicas holds |
| Redis | appendonly yes, appendfsync everysec | Command executed in memory; fsync about once a second | About one second of writes |
| Redis | appendfsync always | fsync before replying | None, at a large throughput cost |
| Application buffer | Ack on enqueue | Item is in process memory | Everything not yet flushed |
Fix / how to use it: write the window as a number in the design ("at most 10 s of view counts"), make graceful shutdown drain the buffer, and for data that must not be lost put a durable log first (the WAL-first alternative, see Durability, WAL & Crash Recovery; the replayable log is the pattern in Transactional Outbox).
-- PostgreSQL: accept a small loss window for this one transaction only.
BEGIN;
SET LOCAL synchronous_commit = off;
INSERT INTO page_events (event_id, page_id, views) VALUES ('e-1', 'p-7', 1);
COMMIT; -- returns before the WAL flush; the database is consistent after a crashBatching Must-know
In plain words: pay the fixed cost of a round trip, a parse and a commit once for many items instead of once per item.
Common misunderstanding: "Batching only matters over a slow network." The server-side fixed cost (parse, plan, WAL flush, lock acquisition) exists on loopback too; PostgreSQL's own guidance is to avoid a series of INSERT statements even for local loads.
Definition: group items into one operation, flush when the group reaches a size limit or an age limit, whichever comes first. The two limits give a latency ceiling (the age) and a cost floor (the size).
Per-item Batched (MaxBatch 500, Linger 200 ms)
1 INSERT ... 1 RTT, 1 commit items 1..500 arrive over 30 ms
2 INSERT ... 1 RTT, 1 commit INSERT ... VALUES (...),(...) x500 1 RTT, 1 commit
3 ... x 500 500 RTT, 500 commits items 501..600 arrive, then 200 ms of quiet
4 timer fires: INSERT ... x100 1 RTT, 1 commitReal scenario: log shipping, metrics collectors, bulk CSV imports, event ingest, ORM insert() of arrays, Kafka producers, Redis pipelines.
How each product batches:
| Product | Mechanism | Flush trigger | Knob |
|---|---|---|---|
| PostgreSQL | COPY ... FROM | One command streams all rows | COPY options; wrap in one transaction |
| PostgreSQL | Multi-row INSERT ... VALUES (...), (...) | One statement | Bind-parameter limit of 65,535 (Int16 count in the protocol Bind message) |
| MySQL / InnoDB | Multi-row INSERT, LOAD DATA | One statement | max_allowed_packet |
| Kafka producer | Record batches per partition | batch.size bytes full, or linger.ms elapsed | batch.size 16384, linger.ms 5, compression.type |
| Redis | Pipeline | Client sends many commands before reading replies | Chunk of about 10k commands |
| Redis | MSET, HSET with many fields, PFADD with many elements | One command | Command argument size |
| Laravel | DB::table()->insert([...]), upsert(), Redis::pipeline(), Bus::batch() | One call | Chunk with array_chunk |
Go database/sql | pgx.CopyFrom, pgx.Batch, hand-built multi-row statement | One call | Your own size limit |
Fix / how to use it: pick the size from the fixed-cost arithmetic (hundreds to a few thousand rows for INSERT, tens of thousands for COPY), pick the linger from the latency you can afford, and always flush on both. The sizing numbers and the Go batcher are in Go and Mechanics.
-- One statement, one commit, N rows. Idempotent: replaying it adds nothing.
INSERT INTO page_events (event_id, page_id, views)
VALUES ('e1', 'p1', 1), ('e2', 'p1', 1), ('e3', 'p2', 1)
ON CONFLICT (event_id) DO NOTHING;
-- Bulk load of already-clean data: COPY is the fastest path.
COPY page_events (event_id, page_id, views) FROM STDIN WITH (FORMAT csv);Coalescing Must-know
In plain words: if ten pending writes say something about the same key, send the database one write that says all of it.
Common misunderstanding: "Coalescing is the same as batching." Batching sends the same number of changes in fewer messages; coalescing sends fewer changes. 1,000 increments of one counter batched are still 1,000 row updates; coalesced they are one.
Definition: keep a map from key to a pending value and merge each new write into it. The merge rule must be associative and match the meaning of the data: add for deltas, keep-highest-version for absolute values (last-writer-wins).
Buffer state (key -> pending)
1 add(page:7, +1) { page:7: +1 }
2 add(page:7, +1) { page:7: +2 }
3 add(page:9, +1) { page:7: +2, page:9: +1 }
4 add(page:7, +1) { page:7: +3, page:9: +1 }
5 flush -> UPDATE page:7 +3, page:9 +1 2 rows, not 4
6 put(user:5, v2) { user:5: v2 }
7 put(user:5, v1) ignored: v1 is not newer than v2 (last-writer-wins by version)Real scenario: counters (views, likes, stock reservations); "last seen" timestamps; profile edits saved on every keystroke; sensor readings where only the latest per device matters; cache write-behind.
Merge rules:
| Data | Merge rule | Safe to coalesce? | Condition |
|---|---|---|---|
| Counter increments | Add the deltas | Yes | The consumer only needs the sum |
| Last-seen timestamp, current status | Keep the highest version or timestamp | Yes | Version or clock must be trustworthy |
| Append-only events | None; every event matters | No | Dedupe by id only |
| Balance with a CHECK constraint | Add the deltas | Careful | Each intermediate state may have mattered; keep a ledger |
| Set membership (add, remove) | Last operation per element wins | Yes | Needs per-element order |
Fix / how to use it: the Go coalesce package shows Deltas (sum) and LastWriter (version). Swap the map out atomically on flush, and merge a failed flush back in with Restore so a transient database error loses nothing.
Write-behind and write-through Important
In plain words: a write-behind cache accepts the write into the cache, tells the caller it is done, and updates the database later; write-through updates both before answering.
Common misunderstanding: "Write-behind is a cache feature." It is a buffer plus coalescer that happens to sit in a cache. The policy lives or dies on the same durability window; the cache page (Caching) owns eviction, invalidation and stampedes.
Definition: write-behind (write-back) acknowledges after the cache write and flushes dirty entries asynchronously, usually coalesced per key; write-through writes the database synchronously and keeps the cache coherent.
Write-through Write-behind
1 PUT user:5 {name:A} PUT user:5 {name:A}
2 write DB (sync) write cache, mark dirty
3 write cache ack
4 ack PUT user:5 {name:B} -> dirty entry replaced (coalesced)
5 flush: one DB write of {name:B}Real scenario: a leaderboard that updates the database every few seconds; a shopping cart kept in Redis and persisted on checkout; a game server that saves player state periodically.
| Product | Write-behind support | Notes |
|---|---|---|
| Redis | Pattern only (your code flushes) | Persistence (appendonly) protects the buffer, not the database sync |
| Hibernate / JPA | Write-behind through the session flush | Transaction-scoped, not cross-request |
| Laravel | Pattern only: Cache::increment or Redis plus a scheduled flush | See Laravel |
| Hazelcast, Apache Ignite | Built-in write-behind with coalescing options | Check each product's queue-limit and batch settings in its docs |
Fix / how to use it: only for data whose loss window you accepted, with graceful flush on shutdown and a metric for dirty-entry age.
Sharded counters Must-know
In plain words: if everybody adds to one number, they queue up; if everybody adds to one of N numbers chosen at random, they mostly do not, and you add the N numbers up when someone asks.
Common misunderstanding: "A faster database fixes a hot counter." A hot row is limited by how long each transaction holds its row lock, a serial resource. A faster CPU shortens the hold a little; N rows divide the queue by N. Firestore documents the same ceiling: "Each shard can support being incremented once per second".
Definition: a sharded (distributed) counter stores one logical value as N sub-counters. A write increments a randomly chosen sub-counter; a read sums all of them. Throughput scales with N; read cost also scales with N.
Hot row (N = 1) Sharded (N = 4)
1 T1 UPDATE views = views+1 lock row T1 UPDATE shard 2 lock shard 2
2 T2 UPDATE views = views+1 waits T2 UPDATE shard 0 lock shard 0 (parallel)
3 T3 UPDATE views = views+1 waits T3 UPDATE shard 2 waits for T1 only
4 T1 COMMIT T1 COMMIT
5 T2 gets the lock read: SELECT sum(views) FROM shards WHERE counter = 'p7'Real scenario: a viral post's like count; a global request counter; a rate-limit window counter; stock count in a flash sale (careful: see below); an ad impression counter.
How products do it:
| Product | Counter facility | Sharding approach | Limit |
|---|---|---|---|
| PostgreSQL | UPDATE ... SET n = n + 1 | Table of (counter_id, shard, n), random shard on write, SUM on read | Row lock per shard; MVCC leaves a dead tuple per update, so keep it VACUUM-friendly |
| MySQL / InnoDB | Same | Same | Row lock per shard; gap locks are not involved on a primary-key update |
| Redis | INCRBY key n, 64-bit signed integers | N keys with a hash tag cnt:{id}:0..N-1, MGET to sum | A single key is one thread's serial work; a Redis Cluster key lives on one shard (slot) |
| DynamoDB | UpdateItem with ADD | Random suffix on the partition key, Query all suffixes | 1,000 WCU per partition key |
| Firestore | Transaction or FieldValue.increment | Subcollection of shard documents | About one sustained write per second per document |
| Cassandra | Counter columns | Counter columns are distributed by design; contention is on the partition | Counters are not idempotent on retry |
| Go (in process) | atomic.Int64 | Padded array of atomics, random index | False sharing if the shards share a cache line |
Fix / how to use it: N of 8 to 64 is a common start (size it from target write rate divided by per-shard rate). Keep a flush job that folds the shards into one row for cheap reads. Random choice spreads load; choosing the shard from the worker id avoids even the random call.
CREATE TABLE counter_shards (
counter_id text NOT NULL,
shard int NOT NULL,
n bigint NOT NULL DEFAULT 0,
PRIMARY KEY (counter_id, shard)
);
-- Write: a random shard 0..15 chosen by the application.
INSERT INTO counter_shards (counter_id, shard, n) VALUES ('p7', 11, 1)
ON CONFLICT (counter_id, shard) DO UPDATE SET n = counter_shards.n + 1;
-- Read: sum on read.
SELECT coalesce(sum(n), 0) FROM counter_shards WHERE counter_id = 'p7';$ redis-cli INCRBY "cnt:{p7}:11" 1
(integer) 1
$ redis-cli MGET "cnt:{p7}:0" "cnt:{p7}:1" ... "cnt:{p7}:15" # sum the non-nil valuesThe picture contrasts one hot row, where every writer queues on one lock, with N sub-counters, where writers pick one at random and a reader adds them up.
Approximate counters and HyperLogLog Important
In plain words: when nobody needs the exact number, count with a small structure that is right to within a percent, instead of storing everything.
Common misunderstanding: "Approximate means unreliable." A HyperLogLog's error is a known, bounded statistical error, constant for any size. A hand-rolled sampler with no stated error is the unreliable one.
Definition: a counter whose value is an estimate with a stated error bound. Types: sampled counters (count 1 in k, multiply by k), Morris counters (increment with probability 2^-c), and HyperLogLog for distinct counts. Redis documents HyperLogLog as "a probabilistic data structure that estimates the cardinality of a set", using "up to 12 KB of memory" with "a standard error rate of 0.81%".
Distinct visitors, exact vs HyperLogLog
1 SADD visitors:2026-11-26 u1 u2 u3 ... memory grows with the number of visitors
2 PFADD visitors:2026-11-26 u1 u2 u3 ... constant up to 12 KB
3 PFCOUNT visitors:2026-11-26 -> about N, within about 1%
4 PFMERGE week day1 day2 ... day7 union of days, still approximateReal scenario: unique visitors per page per day; distinct search queries; "N people are viewing"; approximate like counts shown as "1.2M".
| Technique | Answers | Error | Memory | Mergeable |
|---|---|---|---|---|
Exact set (SADD, SCARD) | Distinct count, membership | None | Grows with N | Yes |
HyperLogLog (PFADD, PFCOUNT, PFMERGE) | Distinct count | Standard error 0.81% in Redis | Up to 12 KB per key | Yes |
| Count-Min Sketch | Frequency of an item | Overcount bounded by width | Fixed | Yes (add) |
| Sampling (1 in k) | Totals | Grows as the rate falls | Tiny | Yes |
| Sharded exact counter | Total | None after all writes land | N rows | Yes |
Fix / how to use it: exact for money and stock, approximate for display and analytics; show rounded numbers in the UI so the error is invisible; internals of probabilistic structures are in Bloom Filters & Probabilistic Structures.
Bounded staleness Important
In plain words: "this number may be at most 10 seconds old" is a promise you can design around; "eventually" is not.
Common misunderstanding: "Eventual consistency means no bound." You can enforce a bound: flush on a timer, expose the last-flush time, and alert when it is late. The bound is an SLO (SLOs & SLIs), not a hope.
Definition: bounded staleness is a contract that a read reflects all writes older than a fixed time (or a fixed number of operations). In a buffered pipeline staleness equals the flush interval, plus queue wait, plus replica lag.
t=0.0s client A increments (buffered)
t=0.0s client A reads the page total: sees old value read-your-writes broken
t=10.0s flush commits the batch
t=10.2s replica applies it
t=10.2s everyone sees it: staleness bound = interval + replica lag = about 10.2 sReal scenario: a dashboard that says "updated 8 s ago"; a creator console showing views with a delay; a leaderboard refreshed every 30 s.
| Place the staleness comes from | Typical size | How to shorten it |
|---|---|---|
| Buffer flush interval | 1–60 s | Smaller Linger, or flush on size |
| Queue wait under load | Grows with backlog | More flushers, bigger batches |
| Replica lag | Milliseconds to seconds | Read from the primary for the writer |
| Cache TTL | Seconds to minutes | Lower TTL, or update the cache on flush |
Fix / how to use it: read-your-own-write by overlaying the buffer: the writer's session adds its pending delta to the displayed value. Publish the flush timestamp so a stale dashboard says so.
Idempotent batch writes and dedup keys Must-know
In plain words: a batch can be sent twice (retry, crash, replay); the second time must change nothing.
Common misunderstanding: "ON CONFLICT DO UPDATE makes the write idempotent." It makes it atomic. SET views = views + 1 applied twice still adds twice. Only absolute values (SET views = 42) or a dedup key make a repeat harmless.
Definition: a batch write is idempotent if applying it N times leaves the same state as applying it once. Two ways: write absolute values (upsert), or record an event id under a unique constraint and apply deltas only for ids that were newly inserted. PostgreSQL's INSERT ... ON CONFLICT "guarantees an atomic INSERT or UPDATE outcome", and a command that touches the same row twice raises a cardinality violation (SQLSTATE 21000, "ON CONFLICT DO UPDATE command cannot affect row a second time"), so a batch must be deduplicated first.
Batch B1 = {e1, e2, e3}, delivered twice
1 BEGIN
2 INSERT INTO page_events ... ON CONFLICT (event_id) DO NOTHING RETURNING event_id
3 first delivery: returns e1, e2, e3 -> apply deltas for 3 events
4 COMMIT
5 (retry of B1)
6 INSERT INTO page_events ... ON CONFLICT DO NOTHING RETURNING event_id
7 second delivery: returns nothing -> apply no deltasReal scenario: Kafka consumer redelivery after a rebalance; a flusher that crashed after the database commit but before trimming its buffer; an HTTP client retrying a bulk endpoint.
| Technique | Idempotent? | Cost | When |
|---|---|---|---|
Upsert of absolute values (upsert()) | Yes | None | Rollups, snapshots, last-writer-wins |
| Delta plus dedup table in one transaction | Yes | One extra insert per event | Counters from at-least-once sources |
| Offset or sequence stored with the result | Yes | One row | Single-partition streams |
| Delta alone | No | None | Never, unless loss is acceptable |
| Idempotency key per batch | Yes, per batch | One row per batch | Bulk API endpoints |
Fix / how to use it:
-- Apply deltas only for events that were new, in one transaction.
WITH fresh AS (
INSERT INTO page_events (event_id, page_id, views)
VALUES ('e1','p1',1), ('e2','p1',1), ('e3','p2',1)
ON CONFLICT (event_id) DO NOTHING
RETURNING page_id, views
), sums AS (
SELECT page_id, sum(views) AS v FROM fresh GROUP BY page_id
)
INSERT INTO page_counters (page_id, views)
SELECT page_id, v FROM sums ORDER BY page_id
ON CONFLICT (page_id) DO UPDATE SET views = page_counters.views + EXCLUDED.views;Ordering inside batches and per-key ordering Important
In plain words: batching and parallel flushers can reorder writes; you must decide which orders matter and protect those.
Common misunderstanding: "A queue preserves order." One queue read by one consumer does. Multiple partitions, multiple consumers, or retries of failed batches do not, except per key if you partition by key.
Definition: per-key ordering means writes for one key are applied in the order they were produced; there is no guarantee across keys. Kafka gives it per partition, so the producer must use the key as the partition key.
Producer Partition by key Consumers
1 user:5 set A -> P2 (hash of user:5) -> consumer X applies A
2 user:5 set B -> P2 -> consumer X applies B (order kept)
3 user:9 set C -> P0 -> consumer Y applies C (parallel with user:5)
Failure case: batch [A, B] fails, retried after batch [C]: per-key order is still A then B,
but only if the retry resends the whole failed batch before anything newer for that key.Real scenario: account balance events; document edit operations; status transitions (created, paid, shipped) where "shipped before paid" is a bug.
| Layer | Ordering guarantee | How to keep it |
|---|---|---|
| In-process channel, one consumer | Arrival order | One flusher goroutine, as in the Go batcher |
| Kafka partition | Order within a partition | Key = entity id; max.in.flight.requests.per.connection of 5 or less with idempotence enabled |
| RabbitMQ queue with one consumer | Order, until a requeue | Single active consumer |
| Redis list | FIFO | Single drain |
| Parallel flush workers | None across batches | Route by key hash to a fixed worker |
| Multi-row upsert | None between rows of one statement | Do not depend on row order inside a statement; sort keys to avoid lock-order deadlocks |
Fix / how to use it: sort the keys inside a batch before updating (a fixed lock order prevents deadlocks between two flushers, see Deadlocks); route by key; put a version number on each write and let the database ignore stale ones (WHERE excluded.version > t.version). Broker-level ordering is in Message Ordering.
Data locality and co-location Important
In plain words: put things that are read or written together on the same machine, page or partition, so one operation touches one place.
Common misunderstanding: "Spreading data evenly is always best." Even spreading wins for single-key operations. If a request needs ten keys, ten partitions means ten network hops and a distributed transaction. Locality means choosing the partition key from the access pattern, not from a hash of the primary key.
Definition: data locality is the property that data accessed together is stored together: in the same shard (partition key), the same disk page (clustering), the same cache line or the same CPU socket (NUMA). Partitioning by an entity id co-locates everything about that entity.
Partition by order_id Partition by user_id
1 user 5 places orders 1, 2, 3 user 5 places orders 1, 2, 3
2 orders on shards 1, 0, 3 all three on shard 3
3 "show my orders" -> 3 shards (scatter) "show my orders" -> 1 shard
4 "order 2 details" -> 1 shard "order 2 details" -> 1 shard (needs user id)Real scenario: a multi-tenant SaaS partitioned by tenant_id; chat messages partitioned by conversation; Kafka topics keyed by account id so per-account order and state stay on one consumer; a cache keyed so related keys share a slot with a hash tag.
| Layer | Locality tool | Product example | Effect |
|---|---|---|---|
| Shard or partition | Partition key | Citus distribution column, DynamoDB partition key, Cassandra partition key, Kafka message key | One node serves a whole entity |
| Disk page | Clustering key, CLUSTER, INCLUDE, InnoDB primary key | InnoDB clustered index stores rows in primary-key order | Range scans read adjacent pages |
| LSM engine | Key prefix, column families | RocksDB prefix extractor; Cassandra clustering columns | A write goes to one memtable and a scan reads one run; see Storage Engines |
| Cache | Hash tag | Redis Cluster {id} forces one slot | Multi-key commands and pipelines stay legal |
| Request routing | Affinity routing | Consistent hashing, sticky sessions, Kafka consumer assignment | Same entity, same process, warm cache |
| CPU | NUMA, cache lines | Per-core counters, padding | Fewer cross-socket and cache-line transfers |
Fix / how to use it: pick the partition key from the dominant query and the dominant write, and accept that the secondary access path becomes a scatter-gather or a second copy. The shard-key decision itself lives in Sharding at System Level; ring mechanics in Consistent Hashing. Kafka locality in practice is covered in Message Ordering.
Cache locality and false sharing Good to know
In plain words: a CPU reads memory in 64-byte lines; two variables on one line make two cores fight over it even if each core only touches its own variable.
Common misunderstanding: "Atomics are free." An atomic add on a line another core owns forces the line to travel between cores. The same sharding idea that fixes a database row fixes a cache line.
Definition: false sharing is contention between cores caused by independent variables sharing a cache line; padding each shard to a line, or giving each core its own shard, removes it. The 64-byte figure is the common size on x86-64 and many ARM cores; check the target CPU.
Counter shards [0],[1] in one 64-byte line Padded: [0] and [1] on separate lines
1 core A: atomic add shard 0 core A: atomic add shard 0
2 core B: atomic add shard 1 line bounces A<->B core B: atomic add shard 1 no bounceReal scenario: a metrics library with a global request counter at 100k increments per second per core; a per-CPU counter in the Linux kernel; Java LongAdder, which is the same idea.
| Layout | Cost per Add (16 goroutines, this chapter's benchmark) | Notes |
|---|---|---|
| 1 padded shard | 60.9 ns | Every core contends for one line |
| 16 padded shards | 14.6 ns | Cores mostly touch different lines |
Measured on the author's Apple Silicon laptop with go test -bench, 12 logical CPUs, single run: treat it as an illustration of the ratio, not as a benchmark of your hardware.
Fix / how to use it: the paddedInt64 type in the Go counter package pads each shard to 64 bytes; in a hot path run go test -bench -cpu 1,4,12 on the real machine before choosing N.
Hot partitions and key salting Must-know
In plain words: if one key gets most of the traffic, the partition that owns it is the bottleneck however many partitions you have; add a random suffix so that one logical key lives in several places.
Common misunderstanding: "Hashing spreads the load, so there are no hot partitions." Hashing spreads different keys. One celebrity key hashes to exactly one place. DynamoDB's guide says to distribute writes by adding a random number to the partition key values, and its adaptive capacity can only isolate a hot item up to the partition maximum of 3,000 RCUs and 1,000 WCUs.
Definition: key salting appends a salt (random, or a calculated bucket) to the key: video:42#0 to video:42#7. Writes pick any salt; reads query all salts and merge. It is the sharded-counter idea applied to any partitioned store.
Without salt With 8 salts
1 write video:42 -> partition A write video:42#3 -> partition C
2 write video:42 -> partition A write video:42#6 -> partition F
3 write video:42 -> partition A (hot) write video:42#1 -> partition B
4 A throttles; others idle load spreads; read = Query 8 keys, mergeReal scenario: a viral video's comment counter; a flash-sale product's stock row; a Kafka topic where one tenant sends 70% of the traffic; a time-series table where "now" is the hot key (see Time-series writes).
| Store | Hot-key symptom | Mitigation |
|---|---|---|
| DynamoDB | ProvisionedThroughputExceededException, throttling on one partition key | Random or calculated suffix (write sharding); on-demand mode does not remove the partition ceiling |
| Cassandra | One node at 100% CPU, WriteTimeoutException | Add a bucket to the partition key |
| Kafka | One partition lagging while others idle | Salt the key (loses per-key order), or a custom partitioner |
| Redis Cluster | One node hot, one slot owner | Shard the key across hash tags that map to different slots |
| PostgreSQL | Lock waits on one row; pg_locks shows many waiters | Sharded counter rows or batching |
| HBase / Bigtable | One region server hot on a monotonically increasing key | Reverse or hash-prefix the key |
Fix / how to use it: salt only the keys that are hot (detect them with a count-min sketch or top-K; see Top-K & Heavy Hitters), keep the salt count small and fixed per key, and store the salt count in config so readers know how many to query.
The picture shows one celebrity key landing on a single partition without a salt, and the same key spread over four partitions with a salt suffix; the price is that a read must query every salt and merge.
Time-series write patterns Good to know
In plain words: time-ordered data is written at the end and read by time range, so store it append-only, in time buckets, and make old data smaller.
Common misunderstanding: "Time is a good partition key." A raw timestamp as the partition key sends every write to the newest partition, a built-in hot partition. Time belongs in the clustering position or in a bucket that is combined with another key.
Definition: an append-only table never updates rows; time bucketing groups rows by hour or day (so a partition holds a bounded slice); downsampling replaces fine-grained old data with coarse aggregates (per-minute to per-hour) to bound storage.
Raw events (append-only) Rollup 1 min Rollup 1 h Retention
1 t=00:00:01 p7 +1 raw: 7 days
2 t=00:00:07 p7 +1 00:00 p7 = 2 1 min: 30 days
3 t=00:01:02 p7 +1 00:01 p7 = 1 00:00-01:00 p7 = 3 1 h: 2 yearsReal scenario: metrics (Prometheus blocks, InfluxDB, TimescaleDB hypertables), analytics events, IoT telemetry, audit trails, order events.
| Pattern | What it does | Example |
|---|---|---|
| Append-only | Never update a row; add a new one | LSM engines write sequentially, see Storage Engines |
| Time bucket in the key | (device_id, day) as partition key | Cassandra and DynamoDB time-series models |
| Partitioned tables | One table partition per day or month | PostgreSQL declarative partitioning; dropping a partition is instant |
| Hypertable | Automatic time chunks | TimescaleDB |
| Downsampling | Roll up old data, delete raw | Prometheus recording rules, InfluxDB tasks |
| Batch by device or series | Group rows of one series in one write | Keeps one series' rows on one page |
Fix / how to use it: insert in batches in time order, create the next partition ahead of time, aggregate with an upsert of absolute rollup values (idempotent), and drop old partitions instead of deleting rows.
CREATE TABLE page_hourly (
page_id text NOT NULL,
hour timestamptz NOT NULL,
views bigint NOT NULL,
PRIMARY KEY (page_id, hour)
) PARTITION BY RANGE (hour);
-- Rollup job, safe to re-run: absolute values, so a repeat changes nothing.
INSERT INTO page_hourly (page_id, hour, views)
SELECT page_id, date_trunc('hour', created_at), sum(views)
FROM page_events WHERE created_at >= '2026-11-26 10:00+00' AND created_at < '2026-11-26 11:00+00'
GROUP BY 1, 2
ON CONFLICT (page_id, hour) DO UPDATE SET views = EXCLUDED.views;Mechanics
Sizing a batch
A batch pays one fixed cost F (round trip, parse, commit) plus a per-row cost r. Per-row cost with batch size B is F / B + r. With a 1 ms fixed cost and 20 microseconds per row (illustrative numbers, not measurements):
| B | Cost per row | Rows per second per connection | Added latency at 5,000 events/s |
|---|---|---|---|
| 1 | 1,020 microseconds | about 980 | 0 |
| 10 | 120 microseconds | about 8,300 | up to 2 ms |
| 100 | 30 microseconds | about 33,000 | up to 20 ms |
| 1,000 | 21 microseconds | about 48,000 | up to 200 ms |
| 10,000 | 20.1 microseconds | about 50,000 | up to 2 s |
The curve flattens after a few hundred rows: past that point more size only adds latency and the size of what one failure rolls back. Choose MaxBatch where the cost per row is within about 10% of the floor, then set Linger to the latency you can afford (at 5,000 events per second a 200 ms linger already fills about 1,000 rows).
Knobs, with defaults
| Product | Knob | Default or typical | What it does |
|---|---|---|---|
| Kafka producer | linger.ms | 5 (0 before Kafka 4.0) | Wait up to this long for a partition batch to fill |
| Kafka producer | batch.size | 16384 bytes | Per-partition batch size; "A small batch size will make batching less common and may reduce throughput" |
| Kafka producer | compression.type | none | Compress whole batches; larger batches compress better |
| Kafka producer | acks, enable.idempotence | all, true (recent clients) | Durability and duplicate suppression on retry |
| PostgreSQL | synchronous_commit | on | off trades up to three times wal_writer_delay for latency |
| PostgreSQL | wal_writer_delay | 200 ms | Interval of the background WAL flush |
| PostgreSQL | max_wal_size, maintenance_work_mem | server defaults | The Populating a Database guide advises raising both for bulk loads |
| PostgreSQL | Bind parameters per statement | 65,535 | Int16 parameter count in the protocol Bind message; 3 columns means at most 21,845 rows per multi-row INSERT |
| Redis | Pipeline size | about 10,000 commands | Replies are queued in server memory until read |
| Redis | appendfsync | everysec | Durability of buffered counters |
| Laravel | Schedule::command(...)->everyTenSeconds() | n/a | The staleness bound of a flushed counter |
| Laravel | upsert() chunking | your array_chunk size | Keeps statements below parameter and packet limits |
| DynamoDB | Per-partition throughput | 3,000 RCU and 1,000 WCU | Ceiling for a single item key |
What goes wrong, verbatim
| Where | Message or symptom | Meaning | What to do |
|---|---|---|---|
| PostgreSQL | ON CONFLICT DO UPDATE command cannot affect row a second time (SQLSTATE 21000) | The batch contains the same key twice | Deduplicate or coalesce before the statement |
| PostgreSQL | deadlock detected (40P01) | Two flushers updated the same rows in different order | Sort keys; retry the batch |
| PostgreSQL drivers | A driver-side error about more than 65535 parameters (wording varies by driver) | Too many bind parameters in one statement | Chunk the batch |
| Redis | WRONGTYPE Operation against a key holding the wrong kind of value | A shard key was written with another type | Namespace keys; do not reuse |
| Redis | ERR increment or decrement would overflow | 64-bit signed limit reached | Rotate the counter or flush and reset |
| Redis Cluster | CROSSSLOT Keys in request don't hash to the same slot | A multi-key command spans slots | Use a hash tag (cnt:{p7}:3) |
| Kafka | RecordTooLargeException | One record above max.request.size | Split or compress the record |
| Kafka | TimeoutException after delivery.timeout.ms (120 s default) | The batch could not be delivered in time | Handle the callback; the batch is not retried further |
| DynamoDB | ProvisionedThroughputExceededException | A partition ceiling was exceeded | Salt the key; back off |
| Go | batcher: queue full (ErrFull) | Bounded buffer reached its limit | Shed, block with a deadline, or spill |
| Laravel | Illuminate\Database\QueryException with SQLSTATE 22P02 or 23505 | Bad value, or duplicate key in a plain insert | Use insertOrIgnore or upsert |
The Redis and Kafka messages above follow the product's documented error names; confirm the exact text on your version.
The flush loop, step by step
State: batch=[], timer stopped
1 item arrives, batch empty -> start the linger timer
2 item arrives -> append
3 len(batch) >= MaxBatch -> emit now, reset the timer
4 timer fires, batch non-empty -> emit the partial batch
5 emit: swap the slice out -> new items go to a fresh slice, writers are not blocked by the flush
6 flush(ctx, batch) returns error -> onError(batch, err): retry, spill or drop, by policy
7 Close(): stop intake, drain -> emit what is queued, wait for the last flushGo
Before
One synchronous UPDATE per event, and one INSERT with its own commit per imported row. Correct and exact, and the first thing that falls over under load.
// Package main shows the naive shape: one synchronous database write per
// event, all of them hitting the same counter row.
package main
import (
"context"
"database/sql"
"fmt"
"net/http"
)
type server struct{ db *sql.DB }
// handleView does one round trip and one row lock per page view.
// Every request for the same page queues behind the previous UPDATE,
// so a hot page serialises on a single row.
func (s *server) handleView(w http.ResponseWriter, r *http.Request) {
pageID := r.URL.Query().Get("page")
_, err := s.db.ExecContext(r.Context(),
`UPDATE pages SET views = views + 1 WHERE id = $1`, pageID)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
// importEvents does one INSERT per event and one commit per INSERT.
func importEvents(ctx context.Context, db *sql.DB, ids []int64) error {
for _, id := range ids {
if _, err := db.ExecContext(ctx,
`INSERT INTO events (id, payload) VALUES ($1, 'x')`, id); err != nil {
return fmt.Errorf("insert %d: %w", id, err)
}
}
return nil
}
func main() {
s := &server{}
http.HandleFunc("/view", s.handleView)
_ = http.ListenAndServe(":8080", nil)
}After
Five small packages, each with tests: a bounded batcher with size and time flush and a graceful drain, a coalesce package (delta sum and last-writer-wins), a counter package (padded in-memory shards and a Redis implementation that sums on read), and an ingest package that builds the idempotent multi-row SQL. cmd/ingestd wires them together.
The batcher:
// Package batcher buffers items in a bounded queue and flushes them in
// batches when the batch is full or when the linger time has passed.
package batcher
import (
"context"
"errors"
"sync"
"time"
)
// ErrFull is returned by TryAdd when the bounded queue has no room.
var ErrFull = errors.New("batcher: queue full")
// ErrClosed is returned by Add and TryAdd after Close.
var ErrClosed = errors.New("batcher: closed")
// FlushFunc writes one batch. It must be safe to call with a batch that
// has already been written once (batches may be retried by the caller).
type FlushFunc[T any] func(ctx context.Context, batch []T) error
// Config holds the three knobs every batcher has.
type Config struct {
MaxBatch int // flush when this many items are waiting
Linger time.Duration // flush a partial batch after this long
QueueDepth int // bounded queue: the backpressure limit
}
// Batcher is a single-consumer batching loop with a graceful drain.
type Batcher[T any] struct {
cfg Config
flush FlushFunc[T]
onError func(batch []T, err error)
in chan T
done chan struct{}
mu sync.RWMutex
closed bool
}
// New starts the flush goroutine. onError may be nil.
func New[T any](cfg Config, flush FlushFunc[T], onError func([]T, error)) *Batcher[T] {
if cfg.MaxBatch <= 0 {
cfg.MaxBatch = 100
}
if cfg.Linger <= 0 {
cfg.Linger = 50 * time.Millisecond
}
if cfg.QueueDepth <= 0 {
cfg.QueueDepth = cfg.MaxBatch * 4
}
b := &Batcher[T]{
cfg: cfg,
flush: flush,
onError: onError,
in: make(chan T, cfg.QueueDepth),
done: make(chan struct{}),
}
go b.loop()
return b
}
// Add blocks while the queue is full (backpressure) or until ctx ends.
func (b *Batcher[T]) Add(ctx context.Context, item T) error {
b.mu.RLock()
defer b.mu.RUnlock()
if b.closed {
return ErrClosed
}
select {
case b.in <- item:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// TryAdd never blocks: it sheds load by returning ErrFull.
func (b *Batcher[T]) TryAdd(item T) error {
b.mu.RLock()
defer b.mu.RUnlock()
if b.closed {
return ErrClosed
}
select {
case b.in <- item:
return nil
default:
return ErrFull
}
}
// Close stops intake, flushes everything still queued, and waits for the
// last flush or for ctx to end, whichever comes first.
func (b *Batcher[T]) Close(ctx context.Context) error {
b.mu.Lock()
if !b.closed {
b.closed = true
close(b.in)
}
b.mu.Unlock()
select {
case <-b.done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (b *Batcher[T]) loop() {
defer close(b.done)
batch := make([]T, 0, b.cfg.MaxBatch)
timer := time.NewTimer(b.cfg.Linger)
defer timer.Stop()
emit := func() {
if len(batch) == 0 {
return
}
out := batch
batch = make([]T, 0, b.cfg.MaxBatch)
// A fresh context: shutdown must not cancel the final flush.
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := b.flush(ctx, out); err != nil && b.onError != nil {
b.onError(out, err)
}
}
for {
select {
case item, ok := <-b.in:
if !ok {
emit() // graceful drain: the channel is closed and empty
return
}
if len(batch) == 0 {
resetTimer(timer, b.cfg.Linger)
}
batch = append(batch, item)
if len(batch) >= b.cfg.MaxBatch {
emit()
}
case <-timer.C:
emit()
timer.Reset(b.cfg.Linger)
}
}
}
func resetTimer(t *time.Timer, d time.Duration) {
if !t.Stop() {
select {
case <-t.C:
default:
}
}
t.Reset(d)
}Its tests (size flush, linger flush, graceful drain, load shedding, error callback, ordering):
package batcher
import (
"context"
"errors"
"sync"
"testing"
"time"
)
type sink struct {
mu sync.Mutex
batches [][]int
}
func (s *sink) flush(_ context.Context, b []int) error {
s.mu.Lock()
defer s.mu.Unlock()
s.batches = append(s.batches, append([]int(nil), b...))
return nil
}
func (s *sink) snapshot() [][]int {
s.mu.Lock()
defer s.mu.Unlock()
return append([][]int(nil), s.batches...)
}
func TestFlushOnSize(t *testing.T) {
s := &sink{}
b := New(Config{MaxBatch: 3, Linger: time.Hour, QueueDepth: 16}, s.flush, nil)
for i := 0; i < 6; i++ {
if err := b.Add(context.Background(), i); err != nil {
t.Fatal(err)
}
}
if err := b.Close(context.Background()); err != nil {
t.Fatal(err)
}
got := s.snapshot()
if len(got) != 2 || len(got[0]) != 3 || len(got[1]) != 3 {
t.Fatalf("want two batches of 3, got %v", got)
}
}
func TestFlushOnLinger(t *testing.T) {
s := &sink{}
b := New(Config{MaxBatch: 100, Linger: 20 * time.Millisecond, QueueDepth: 16}, s.flush, nil)
defer b.Close(context.Background())
_ = b.Add(context.Background(), 1)
deadline := time.After(2 * time.Second)
for len(s.snapshot()) == 0 {
select {
case <-deadline:
t.Fatal("partial batch was never flushed by the linger timer")
case <-time.After(5 * time.Millisecond):
}
}
}
func TestGracefulDrain(t *testing.T) {
s := &sink{}
b := New(Config{MaxBatch: 100, Linger: time.Hour, QueueDepth: 16}, s.flush, nil)
for i := 0; i < 5; i++ {
_ = b.Add(context.Background(), i)
}
if err := b.Close(context.Background()); err != nil {
t.Fatal(err)
}
got := s.snapshot()
if len(got) != 1 || len(got[0]) != 5 {
t.Fatalf("drain must flush the partial batch, got %v", got)
}
if err := b.Add(context.Background(), 9); !errors.Is(err, ErrClosed) {
t.Fatalf("want ErrClosed after Close, got %v", err)
}
}
func TestTryAddShedsLoad(t *testing.T) {
block := make(chan struct{})
flush := func(ctx context.Context, _ []int) error { <-block; return nil }
b := New(Config{MaxBatch: 1, Linger: time.Hour, QueueDepth: 2}, flush, nil)
var full bool
for i := 0; i < 20; i++ {
if err := b.TryAdd(i); errors.Is(err, ErrFull) {
full = true
break
}
}
close(block)
_ = b.Close(context.Background())
if !full {
t.Fatal("bounded queue never reported ErrFull")
}
}
func TestErrorCallbackGetsBatch(t *testing.T) {
var mu sync.Mutex
var failed []int
boom := errors.New("boom")
b := New(Config{MaxBatch: 2, Linger: time.Hour, QueueDepth: 8},
func(context.Context, []int) error { return boom },
func(batch []int, err error) {
mu.Lock()
failed = append(failed, batch...)
mu.Unlock()
})
_ = b.Add(context.Background(), 1)
_ = b.Add(context.Background(), 2)
_ = b.Close(context.Background())
mu.Lock()
defer mu.Unlock()
if len(failed) != 2 {
t.Fatalf("onError should receive the failed batch, got %v", failed)
}
}
func TestPerKeyOrderInsideBatch(t *testing.T) {
s := &sink{}
b := New(Config{MaxBatch: 10, Linger: time.Hour, QueueDepth: 16}, s.flush, nil)
for i := 0; i < 10; i++ {
_ = b.Add(context.Background(), i)
}
_ = b.Close(context.Background())
got := s.snapshot()[0]
for i, v := range got {
if v != i {
t.Fatalf("single-consumer batcher must keep arrival order, got %v", got)
}
}
}Coalescing, with Restore for a failed flush:
// Package coalesce collapses many updates to the same key into one write
// per flush interval. Two merge rules are shown: add deltas, or keep the
// last writer.
package coalesce
import "sync"
// Deltas sums increments per key. Flush returns the totals and resets.
type Deltas struct {
mu sync.Mutex
m map[string]int64
}
func NewDeltas() *Deltas { return &Deltas{m: make(map[string]int64)} }
// Add records one increment; N calls for one key become one entry.
func (d *Deltas) Add(key string, delta int64) {
d.mu.Lock()
d.m[key] += delta
d.mu.Unlock()
}
// Len is the number of distinct keys waiting.
func (d *Deltas) Len() int {
d.mu.Lock()
defer d.mu.Unlock()
return len(d.m)
}
// Flush swaps the map out so writers are blocked only for the swap.
func (d *Deltas) Flush() map[string]int64 {
d.mu.Lock()
out := d.m
d.m = make(map[string]int64)
d.mu.Unlock()
return out
}
// Restore merges a failed flush back so no delta is lost.
func (d *Deltas) Restore(failed map[string]int64) {
d.mu.Lock()
for k, v := range failed {
d.m[k] += v
}
d.mu.Unlock()
}
// Versioned is a value with a monotonically increasing version.
type Versioned struct {
Version int64
Value string
}
// LastWriter keeps only the highest version per key (last-writer-wins).
type LastWriter struct {
mu sync.Mutex
m map[string]Versioned
}
func NewLastWriter() *LastWriter { return &LastWriter{m: make(map[string]Versioned)} }
// Put ignores a write whose version is not newer than the buffered one.
func (l *LastWriter) Put(key string, v Versioned) {
l.mu.Lock()
defer l.mu.Unlock()
if cur, ok := l.m[key]; ok && cur.Version >= v.Version {
return
}
l.m[key] = v
}
func (l *LastWriter) Flush() map[string]Versioned {
l.mu.Lock()
out := l.m
l.m = make(map[string]Versioned)
l.mu.Unlock()
return out
}package coalesce
import (
"sync"
"testing"
)
func TestDeltasCollapseToOneEntry(t *testing.T) {
d := NewDeltas()
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() { defer wg.Done(); d.Add("page:1", 1) }()
}
wg.Wait()
if d.Len() != 1 {
t.Fatalf("1000 updates to one key should be 1 entry, got %d", d.Len())
}
if got := d.Flush()["page:1"]; got != 1000 {
t.Fatalf("want 1000, got %d", got)
}
if d.Len() != 0 {
t.Fatal("flush must reset the buffer")
}
}
func TestRestoreKeepsFailedDeltas(t *testing.T) {
d := NewDeltas()
d.Add("a", 5)
failed := d.Flush()
d.Add("a", 2) // arrives while the flush is failing
d.Restore(failed)
if got := d.Flush()["a"]; got != 7 {
t.Fatalf("want 7, got %d", got)
}
}
func TestLastWriterKeepsHighestVersion(t *testing.T) {
l := NewLastWriter()
l.Put("u", Versioned{Version: 2, Value: "new"})
l.Put("u", Versioned{Version: 1, Value: "old"}) // late arrival
if got := l.Flush()["u"]; got.Value != "new" {
t.Fatalf("stale write won: %+v", got)
}
}The sharded counter, in memory with cache-line padding, and its test and benchmark:
// Package counter contains an in-memory sharded counter and a Redis-backed
// one. Both spread increments over N sub-counters and sum on read.
package counter
import (
"context"
"fmt"
"math/rand/v2"
"sync/atomic"
)
// Counter is the shared contract.
type Counter interface {
Add(ctx context.Context, key string, delta int64) error
Total(ctx context.Context, key string) (int64, error)
}
// paddedInt64 keeps each shard on its own 64-byte cache line so cores that
// hit different shards do not invalidate each other's cache line.
type paddedInt64 struct {
v atomic.Int64
_ [56]byte
}
// Memory is a lock-free sharded counter for one process.
type Memory struct {
shards []paddedInt64
}
func NewMemory(n int) *Memory {
if n < 1 {
n = 1
}
return &Memory{shards: make([]paddedInt64, n)}
}
// Add picks a random shard; there is no lock and no shared hot word.
func (m *Memory) Add(_ context.Context, _ string, delta int64) error {
m.shards[rand.IntN(len(m.shards))].v.Add(delta)
return nil
}
// Total sums every shard. The sum is not a snapshot: increments that land
// during the loop may or may not be included.
func (m *Memory) Total(_ context.Context, _ string) (int64, error) {
var sum int64
for i := range m.shards {
sum += m.shards[i].v.Load()
}
return sum, nil
}
// ShardKey builds the Redis key of one sub-counter. The hash tag in braces
// keeps all shards of one counter in the same Redis Cluster slot so a
// pipeline or MGET over them is legal.
func ShardKey(key string, shard int) string {
return fmt.Sprintf("cnt:{%s}:%d", key, shard)
}package counter
import (
"context"
"sync"
"testing"
)
func TestMemoryConcurrentTotal(t *testing.T) {
c := NewMemory(8)
var wg sync.WaitGroup
for g := 0; g < 16; g++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := 0; i < 10_000; i++ {
_ = c.Add(context.Background(), "k", 1)
}
}()
}
wg.Wait()
got, _ := c.Total(context.Background(), "k")
if got != 160_000 {
t.Fatalf("lost increments: %d", got)
}
}
func TestMemorySpreadsAcrossShards(t *testing.T) {
c := NewMemory(4)
for i := 0; i < 4000; i++ {
_ = c.Add(context.Background(), "k", 1)
}
for i := range c.shards {
if c.shards[i].v.Load() == 0 {
t.Fatalf("shard %d never used", i)
}
}
}
func TestShardKeyHashTag(t *testing.T) {
if got := ShardKey("page:7", 3); got != "cnt:{page:7}:3" {
t.Fatal(got)
}
}
func BenchmarkMemory1Shard(b *testing.B) { bench(b, 1) }
func BenchmarkMemory16Shard(b *testing.B) { bench(b, 16) }
func bench(b *testing.B, n int) {
c := NewMemory(n)
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
_ = c.Add(context.Background(), "k", 1)
}
})
}The same counter on Redis (INCRBY on a random shard, one MGET to sum, a pipeline for many counters), tested against an in-process miniredis, so no server is needed:
package counter
import (
"context"
"math/rand/v2"
"strconv"
"github.com/redis/go-redis/v9"
)
// Redis stores N sub-counters as plain keys and sums them with one MGET.
type Redis struct {
rdb redis.UniversalClient
shards int
}
func NewRedis(rdb redis.UniversalClient, shards int) *Redis {
if shards < 1 {
shards = 1
}
return &Redis{rdb: rdb, shards: shards}
}
// Add is one INCRBY on a random shard. INCRBY is atomic inside Redis.
func (r *Redis) Add(ctx context.Context, key string, delta int64) error {
return r.rdb.IncrBy(ctx, ShardKey(key, rand.IntN(r.shards)), delta).Err()
}
// AddMany sends many increments in one round trip with a pipeline.
func (r *Redis) AddMany(ctx context.Context, deltas map[string]int64) error {
pipe := r.rdb.Pipeline()
for k, d := range deltas {
pipe.IncrBy(ctx, ShardKey(k, rand.IntN(r.shards)), d)
}
_, err := pipe.Exec(ctx)
return err
}
// Total reads every shard with one MGET and sums the non-missing values.
func (r *Redis) Total(ctx context.Context, key string) (int64, error) {
keys := make([]string, r.shards)
for i := range keys {
keys[i] = ShardKey(key, i)
}
vals, err := r.rdb.MGet(ctx, keys...).Result()
if err != nil {
return 0, err
}
var sum int64
for _, v := range vals {
if v == nil {
continue
}
s, ok := v.(string)
if !ok {
continue
}
n, err := strconv.ParseInt(s, 10, 64)
if err != nil {
return 0, err
}
sum += n
}
return sum, nil
}package counter
import (
"context"
"testing"
"github.com/alicebob/miniredis/v2"
"github.com/redis/go-redis/v9"
)
func newRedis(t *testing.T, shards int) (*Redis, *miniredis.Miniredis) {
t.Helper()
mr := miniredis.RunT(t)
rdb := redis.NewClient(&redis.Options{Addr: mr.Addr()})
t.Cleanup(func() { _ = rdb.Close() })
return NewRedis(rdb, shards), mr
}
func TestRedisAddAndTotal(t *testing.T) {
c, _ := newRedis(t, 4)
ctx := context.Background()
for i := 0; i < 100; i++ {
if err := c.Add(ctx, "page:1", 1); err != nil {
t.Fatal(err)
}
}
got, err := c.Total(ctx, "page:1")
if err != nil || got != 100 {
t.Fatalf("got %d err %v", got, err)
}
}
func TestRedisShardsAreSeparateKeys(t *testing.T) {
c, mr := newRedis(t, 4)
ctx := context.Background()
for i := 0; i < 400; i++ {
_ = c.Add(ctx, "page:2", 1)
}
if n := len(mr.Keys()); n < 2 {
t.Fatalf("expected increments spread over several keys, got %d", n)
}
}
func TestRedisAddManyPipeline(t *testing.T) {
c, _ := newRedis(t, 2)
ctx := context.Background()
if err := c.AddMany(ctx, map[string]int64{"a": 10, "b": 5}); err != nil {
t.Fatal(err)
}
a, _ := c.Total(ctx, "a")
b, _ := c.Total(ctx, "b")
if a != 10 || b != 5 {
t.Fatalf("a=%d b=%d", a, b)
}
}
func TestRedisMissingKeyIsZero(t *testing.T) {
c, _ := newRedis(t, 3)
got, err := c.Total(context.Background(), "nothing")
if err != nil || got != 0 {
t.Fatalf("got %d err %v", got, err)
}
}The idempotent SQL builders and the command that wires everything:
// Package ingest turns a batch of events into one idempotent multi-row
// upsert for PostgreSQL.
package ingest
import (
"fmt"
"strings"
)
// Event is one analytics event. EventID is the dedup key.
type Event struct {
EventID string
PageID string
Views int64
}
// Dedupe keeps the first occurrence of each EventID inside one batch, in
// arrival order. Without it PostgreSQL raises "ON CONFLICT DO UPDATE
// command cannot affect row a second time" when a batch repeats a key.
func Dedupe(in []Event) []Event {
seen := make(map[string]struct{}, len(in))
out := make([]Event, 0, len(in))
for _, e := range in {
if _, dup := seen[e.EventID]; dup {
continue
}
seen[e.EventID] = struct{}{}
out = append(out, e)
}
return out
}
// SumByPage coalesces events into one delta per page.
func SumByPage(in []Event) map[string]int64 {
out := make(map[string]int64)
for _, e := range in {
out[e.PageID] += e.Views
}
return out
}
// BuildEventInsert returns a multi-row INSERT that skips events already
// stored. The unique primary key on event_id is the idempotency guard.
func BuildEventInsert(events []Event) (string, []any) {
var sb strings.Builder
sb.WriteString("INSERT INTO page_events (event_id, page_id, views) VALUES ")
args := make([]any, 0, len(events)*3)
for i, e := range events {
if i > 0 {
sb.WriteString(", ")
}
n := i * 3
fmt.Fprintf(&sb, "($%d, $%d, $%d)", n+1, n+2, n+3)
args = append(args, e.EventID, e.PageID, e.Views)
}
sb.WriteString(" ON CONFLICT (event_id) DO NOTHING")
return sb.String(), args
}
// BuildCounterUpsert adds a coalesced delta to each page counter.
// Adding a delta is not idempotent on its own: run it in the same
// transaction as BuildEventInsert and only for the rows it inserted.
func BuildCounterUpsert(deltas map[string]int64, order []string) (string, []any) {
var sb strings.Builder
sb.WriteString("INSERT INTO page_counters (page_id, views) VALUES ")
args := make([]any, 0, len(order)*2)
for i, id := range order {
if i > 0 {
sb.WriteString(", ")
}
fmt.Fprintf(&sb, "($%d, $%d)", i*2+1, i*2+2)
args = append(args, id, deltas[id])
}
sb.WriteString(" ON CONFLICT (page_id) DO UPDATE SET views = page_counters.views + EXCLUDED.views")
return sb.String(), args
}package ingest
import (
"strings"
"testing"
)
func TestDedupeKeepsFirst(t *testing.T) {
in := []Event{{"e1", "p1", 1}, {"e2", "p1", 1}, {"e1", "p1", 1}}
if got := Dedupe(in); len(got) != 2 || got[0].EventID != "e1" || got[1].EventID != "e2" {
t.Fatalf("got %+v", got)
}
}
func TestSumByPage(t *testing.T) {
got := SumByPage([]Event{{"e1", "p1", 1}, {"e2", "p1", 2}, {"e3", "p2", 5}})
if got["p1"] != 3 || got["p2"] != 5 {
t.Fatalf("got %v", got)
}
}
func TestBuildEventInsertShape(t *testing.T) {
q, args := BuildEventInsert([]Event{{"e1", "p1", 1}, {"e2", "p2", 3}})
want := "INSERT INTO page_events (event_id, page_id, views) VALUES ($1, $2, $3), ($4, $5, $6) ON CONFLICT (event_id) DO NOTHING"
if q != want || len(args) != 6 {
t.Fatalf("q=%q args=%v", q, args)
}
}
func TestBuildCounterUpsertShape(t *testing.T) {
q, args := BuildCounterUpsert(map[string]int64{"p1": 3, "p2": 5}, []string{"p1", "p2"})
if !strings.Contains(q, "page_counters.views + EXCLUDED.views") || len(args) != 4 {
t.Fatalf("q=%q args=%v", q, args)
}
}// Command ingestd wires the batcher, the coalescer and a flush function.
// The database call is replaced by a print so the program runs anywhere.
package main
import (
"context"
"fmt"
"os"
"os/signal"
"sort"
"syscall"
"time"
"academy/write-buffering-sharded-counters/batcher"
"academy/write-buffering-sharded-counters/ingest"
)
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
flush := func(ctx context.Context, events []ingest.Event) error {
events = ingest.Dedupe(events)
deltas := ingest.SumByPage(events)
order := make([]string, 0, len(deltas))
for id := range deltas {
order = append(order, id)
}
sort.Strings(order) // stable lock order avoids deadlocks between flushes
q, args := ingest.BuildCounterUpsert(deltas, order)
fmt.Printf("flush %d events -> %d rows: %s %v\n", len(events), len(order), q, args)
return nil // here: tx.ExecContext(ctx, BuildEventInsert(...)) then the counter upsert
}
b := batcher.New(batcher.Config{MaxBatch: 500, Linger: 200 * time.Millisecond, QueueDepth: 4096}, flush,
func(batch []ingest.Event, err error) { fmt.Fprintln(os.Stderr, "flush failed:", len(batch), err) })
for i := 0; i < 1200; i++ {
_ = b.Add(ctx, ingest.Event{EventID: fmt.Sprint("e", i), PageID: fmt.Sprint("p", i%3), Views: 1})
}
// Graceful drain: stop intake, flush what is queued, bounded by 5 s.
drainCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := b.Close(drainCtx); err != nil {
fmt.Fprintln(os.Stderr, "drain incomplete:", err)
os.Exit(1)
}
}Limits of this implementation, stated so nobody mistakes it for a library: the batcher has one flusher goroutine (ordering is simple, throughput is bounded by one flush at a time); a failed flush is reported to onError, not retried (the caller decides between retry, spill and drop); Close waits for the final flush but a process killed with SIGKILL still loses the queue (the durability window); the Redis Total is a sum of one MGET, which is atomic inside Redis but not across a concurrent flush job that resets shards.
The Go angle
- A buffered channel is the bounded queue; its capacity is the backpressure limit, and
selectwithdefaultgivesTryAdd. Closing the channel after setting a flag under async.RWMutexis what makesCloserace-free (verified withgo test -race). sync/atomictypes (atomic.Int64) are lock-free counters; async.Mutexaround a map is fine for coalescing because the critical section is a map write. Swap the map on flush so writers wait for a pointer swap, not for the database call.time.Timer.Resetneeds the stop-and-drain idiom (seeresetTimer) on older semantics; Go 1.23 changed timer channels to be unbuffered and garbage-collectable, but the idiom stays correct.- A shutdown context must not cancel the final flush: the batcher uses a fresh 10-second context for each flush, and
Close(ctx)only bounds how long the caller waits. database/sqlhas no multi-row API; build the statement yourself (asingestdoes) or usepgx(CopyFromfor theCOPYprotocol,pgx.Batchto send several statements in one round trip). Keep every statement below the 65,535 parameter limit.go-redisPipeline()andTxPipeline()both batch commands; the second wraps them inMULTI/EXEC. AClusterClientgroups pipelined commands by node, but a multi-key command such asMGETstill needs a shared slot, which the hash tag inShardKeyprovides.math/rand/v2top-level functions are safe for concurrent use and need no seed.
Laravel
Before
$page->increment('views') on every request: one UPDATE pages SET views = views + 1 and one row lock per view.
<?php
namespace App\Http\Controllers;
use App\Models\Page;
use Illuminate\Http\Response;
final class ViewController
{
// One UPDATE and one row lock per page view: a hot page serialises here.
public function store(Page $page): Response
{
$page->increment('views');
return response()->noContent();
}
}After
Schema first (the primary key on page_events.event_id is the idempotency guard):
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('page_counters', function (Blueprint $table) {
$table->string('page_id')->primary();
$table->unsignedBigInteger('views')->default(0);
$table->timestamp('flushed_at')->nullable();
});
// The primary key on event_id is the idempotency guard.
Schema::create('page_events', function (Blueprint $table) {
$table->string('event_id')->primary();
$table->string('page_id')->index();
$table->unsignedInteger('views')->default(1);
$table->timestamp('created_at')->useCurrent();
});
}
public function down(): void
{
Schema::dropIfExists('page_events');
Schema::dropIfExists('page_counters');
}
};A sharded counter on Redis: Redis::incrby on a random shard, Redis::pipeline for many counters, Redis::mget to sum, and Cache::increment for a single-key local counter (initialised with Cache::add, as the Laravel cache documentation shows):
<?php
namespace App\Counters;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
/**
* N sub-counters per logical counter. Writes pick a random shard; reads sum.
* The {braces} are a Redis Cluster hash tag so all shards share one slot.
*/
final class ShardedCounter
{
public function __construct(private readonly int $shards = 16)
{
}
public function key(string $name, int $shard): string
{
return "cnt:{{$name}}:{$shard}";
}
public function add(string $name, int $delta = 1): void
{
// INCRBY is atomic inside Redis; no read-modify-write in PHP.
Redis::incrby($this->key($name, random_int(0, $this->shards - 1)), $delta);
}
/** @param array<string,int> $deltas one round trip for many counters */
public function addMany(array $deltas): void
{
Redis::pipeline(function ($pipe) use ($deltas) {
foreach ($deltas as $name => $delta) {
$pipe->incrby($this->key($name, random_int(0, $this->shards - 1)), $delta);
}
});
}
public function total(string $name): int
{
$keys = array_map(fn (int $i) => $this->key($name, $i), range(0, $this->shards - 1));
return (int) array_sum(array_map('intval', Redis::mget($keys)));
}
/** A single-key counter in the application cache (store must support atomic increment). */
public function addLocal(string $name, int $delta = 1): int
{
Cache::add("local:{$name}", 0, now()->addHours(4));
return Cache::increment("local:{$name}", $delta);
}
}A scheduled flush command that moves the shards into PostgreSQL with one multi-row upsert that adds the delta, and its schedule (every ten seconds, so the staleness bound is about ten seconds):
<?php
namespace App\Console\Commands;
use App\Counters\ShardedCounter;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
final class FlushViewCounts extends Command
{
protected $signature = 'views:flush {--shards=16}';
protected $description = 'Move buffered Redis view counts into page_counters';
public function handle(): int
{
$shards = (int) $this->option('shards');
$counter = new ShardedCounter($shards);
$deltas = [];
foreach (Redis::smembers('buffer:dirty-pages') as $pageId) {
$delta = 0;
foreach (range(0, $shards - 1) as $i) {
// GETDEL reads and resets one shard in one atomic step.
$delta += (int) Redis::getdel($counter->key($pageId, $i));
}
if ($delta > 0) {
$deltas[$pageId] = $delta;
}
}
if ($deltas === []) {
return self::SUCCESS;
}
ksort($deltas); // stable key order keeps concurrent flushes from deadlocking
$placeholders = implode(', ', array_fill(0, count($deltas), '(?, ?)'));
$bindings = [];
foreach ($deltas as $pageId => $delta) {
array_push($bindings, $pageId, $delta);
}
// Add the delta; do not overwrite. A crash after GETDEL and before
// this commit loses these deltas: that is the durability window.
DB::statement(
"INSERT INTO page_counters (page_id, views) VALUES {$placeholders}
ON CONFLICT (page_id) DO UPDATE SET views = page_counters.views + EXCLUDED.views",
$bindings,
);
$this->info('flushed '.count($deltas).' pages');
return self::SUCCESS;
}
}<?php
use Illuminate\Support\Facades\Schedule;
// Flush every 10 seconds: the staleness bound of the counter is the interval.
Schedule::command('views:flush')->everyTenSeconds()->withoutOverlapping()->onOneServer();A Redis-list event buffer that flushes with insertOrIgnore and trims only after commit:
<?php
namespace App\Buffer;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
/**
* Buffers events in a Redis list and writes them with one multi-row upsert.
* The event_id primary key makes a replayed batch harmless.
*/
final class EventBuffer
{
private const LIST = 'buffer:events';
public function push(string $eventId, string $pageId): void
{
Redis::rpush(self::LIST, json_encode(['event_id' => $eventId, 'page_id' => $pageId]));
}
/** Drain up to $max events and write them in one statement. */
public function flush(int $max = 1000): int
{
$raw = Redis::lrange(self::LIST, 0, $max - 1);
if ($raw === []) {
return 0;
}
$rows = collect($raw)
->map(fn (string $line) => json_decode($line, true, 512, JSON_THROW_ON_ERROR))
->unique('event_id') // a batch must not repeat a key
->map(fn (array $e) => ['event_id' => $e['event_id'], 'page_id' => $e['page_id'], 'views' => 1])
->values()
->all();
DB::transaction(function () use ($rows) {
// insertOrIgnore -> INSERT ... ON CONFLICT DO NOTHING on PostgreSQL
DB::table('page_events')->insertOrIgnore($rows);
});
// Trim only after the commit: a crash in between replays the batch.
Redis::ltrim(self::LIST, count($raw), -1);
return count($rows);
}
}DB::table()->upsert() for absolute values such as hourly rollups (the documented signature is values, unique-by columns, columns to update):
<?php
namespace App\Buffer;
use Illuminate\Support\Facades\DB;
/**
* Absolute values (not deltas) are naturally idempotent: writing the same
* hourly rollup twice leaves the same row, so upsert() is the right tool.
*/
final class RollupWriter
{
/** @param list<array{page_id:string,hour:string,views:int}> $rollups */
public function write(array $rollups): void
{
foreach (array_chunk($rollups, 1000) as $chunk) {
DB::table('page_hourly')->upsert(
$chunk,
['page_id', 'hour'], // unique index required on these columns
['views'], // columns overwritten on conflict
);
}
}
}Queue-based buffering with Bus::batch: one job per chunk, allowFailures() so a bad chunk does not cancel the rest:
<?php
namespace App\Jobs;
use Illuminate\Bus\Batchable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\DB;
final class WriteEventsChunk implements ShouldQueue
{
use Batchable, Queueable;
public int $tries = 3;
/** @param list<array{event_id:string,page_id:string,views:int}> $rows */
public function __construct(private readonly array $rows)
{
}
public function handle(): void
{
if ($this->batch()?->cancelled()) {
return;
}
// Retried or duplicated chunks are harmless: event_id is the primary key.
DB::table('page_events')->insertOrIgnore($this->rows);
}
}<?php
namespace App\Buffer;
use App\Jobs\WriteEventsChunk;
use Illuminate\Bus\Batch;
use Illuminate\Support\Facades\Bus;
use Throwable;
final class BulkIngest
{
/** @param list<array{event_id:string,page_id:string,views:int}> $events */
public function dispatch(array $events): string
{
$jobs = array_map(
fn (array $chunk) => new WriteEventsChunk($chunk),
array_chunk($events, 500),
);
$batch = Bus::batch($jobs)
->name('analytics-ingest')
->onQueue('ingest')
->allowFailures() // one bad chunk must not cancel the others
->then(fn (Batch $b) => logger()->info("ingest done {$b->id}"))
->catch(fn (Batch $b, Throwable $e) => logger()->error("ingest chunk failed {$b->id}"))
->dispatch();
return $batch->id;
}
}Limits: the snippets are syntax-checked with php -l and written against the Laravel 13 documentation, but not executed here (no Laravel app, Redis or PostgreSQL was started). FlushViewCounts uses GETDEL, which deletes the shard as it reads it, so a crash between GETDEL and the database commit loses that interval's counts: that is the durability window, stated in a comment. A stricter version renames the shard keys to a flushing: prefix first and deletes them after the commit, accepting a possible double count unless a dedup key is added.
The Laravel angle
DB::table()->upsert($values, $uniqueBy, $update)compiles toINSERT ... ON CONFLICT ... DO UPDATEon PostgreSQL. The Laravel docs state that all databases except SQL Server require the unique-by columns to have a primary or unique index. The$updatearray lists columns to overwrite with the incoming value, so it fits absolute values; a delta ("add to the existing value") needs a raw statement as inFlushViewCounts.insertOrIgnoreskips duplicate-key errors; the Laravel docs warn it "may also" ignore other kinds of errors depending on the engine, so use it only on a table where a duplicate key is the only expected failure.Redis::pipeline(function ($pipe) {...})sends the commands "at the same time to reduce network trips" and runs them in order; it is not a transaction (useRedis::transactionforMULTI/EXEC).Cache::increment('key', $amount)is atomic only on stores that implement atomic increments (Redis, Memcached, database with a locking statement); thefileandarraystores are not safe across processes.Bus::batch([...])->allowFailures()->dispatch()is job-level batching: it gives progress, cancellation andthen/catch/finallycallbacks, but it is not a database batch. Put the multi-row statement inside each job. It needs thejob_batchestable (php artisan make:queue-batches-table).Schedule::command('views:flush')->everyTenSeconds()->withoutOverlapping()->onOneServer(): sub-minute scheduling needsschedule:runto run every minute (Laravel then loops for the minute) orschedule:work;onOneServerneeds a cache driver that supports atomic locks.- Octane keeps workers alive, so a static array buffer would survive across requests but not across workers; prefer Redis for a buffer shared by workers and flush on a schedule.
Solving the classic problems
The view counter
Symptom: lock waits and 99th-percentile latency spikes on UPDATE pages SET views = views + 1 during a traffic peak.
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Buffer in Redis, flush every few seconds | INCRBY per view, scheduled upsert that adds the delta | Database sees one write per page per interval | Loses up to one interval plus unflushed Redis data on a crash |
| Sharded Redis counter | N shard keys, sum on read | Removes the hot key inside Redis | Read costs N keys |
| In-process coalescing | coalesce.Deltas per app server, flush each 1–5 s | No Redis round trip per view | Loss window equals process crash; N servers make N writers |
| Append events, aggregate later | Insert events in batches, GROUP BY in a job | Nothing is lost silently, can recompute | Storage grows; hourly latency |
| Approximate | Sample 1 in k, or HyperLogLog for distinct | Tiny state | Shown as rounded numbers |
Preferred: Redis INCRBY on a few shards, flush every 5–10 s with a delta upsert, and show the total as database + pending.
The like counter
Symptom: counts drift after retries; a user can like twice; a celebrity post is a hot row.
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Source of truth is a set | Table likes (post_id, user_id) with a unique key | Dedup is a constraint; the count can always be recomputed | A write per like; hot post still hot |
| Counter beside the set | Insert into likes ON CONFLICT DO NOTHING RETURNING, add 1 only if inserted, same transaction | Exact and idempotent | One extra row update; shard it for celebrities |
| Sharded counter for hot posts | Counter rows by (post_id, shard) | Spreads the lock | Sum on read, rare |
| Cached count with rebuild | Redis INCR, nightly recompute from likes | Fast display; self-healing | Temporary drift |
Analytics ingest
Symptom: ten thousand events per second and a database at 100% CPU doing single-row inserts.
| Solution | How | Advantage | Cost or limit |
|---|---|---|---|
| Kafka in front | Producer with linger.ms and batch.size, consumer inserts in batches | Durable buffer, replay, backpressure by lag | Another system to run |
Batched INSERT with ON CONFLICT DO NOTHING | ingest.BuildEventInsert | Idempotent, simple | Needs an event id |
COPY into a staging table, then INSERT ... SELECT ... ON CONFLICT | Fastest load, then merge | Best throughput | Two steps; staging cleanup |
| Time-partitioned table | One partition per day | Cheap retention, small indexes | Partition management |
The flusher crashed
Symptom: the process died between taking items from the buffer and committing them.
| Where the crash fell | Result | Fix |
|---|---|---|
| Before taking items | Nothing lost if the buffer is durable | None |
| After take, before commit | Items lost if the take deleted them | Trim the buffer only after commit; peek, write, then trim |
| After commit, before trim | Items applied twice on restart | Idempotent write (dedup key or absolute value) |
| During graceful shutdown | Partial batch lost if the drain is skipped | Close(ctx) with a deadline; flush on SIGTERM |
The thundering flush
Symptom: every app server flushes on the same second; the database sees a periodic spike.
Add jitter to the flush interval (for example plus or minus 20%), flush by size as well as time, and let onOneServer or a single flusher own the job. The same jitter idea is in Timeouts, Retries & Jitter.
Bulk import
Symptom: a 5-million-row CSV upload takes hours or blocks the web request.
Stream the file, chunk to 500–5,000 rows, load each chunk with COPY or a multi-row INSERT ... ON CONFLICT, wrap each chunk in its own transaction so a failure loses one chunk, and track progress with Bus::batch or a job table. Drop non-essential indexes and constraints during the load and rebuild afterwards, as the PostgreSQL Populating a Database guide describes.
Choosing
Which technique for which workload
| Workload | Recommended | Extra technique | Reason |
|---|---|---|---|
| Page views, impressions | Redis shards, flush every 5–10 s | Display db + pending; HLL for uniques | Loss of seconds is acceptable |
| Likes, votes | Set table plus counter in one transaction | Shard counters for hot posts | Exactness and dedup matter |
| Click and analytics events | Kafka or a Redis list, batched insert | Time partitions, rollups | Durable replayable buffer |
| Money, stock, balances | No write buffering | Atomic UPDATE, ledger, outbox | Loss window unacceptable |
| Metrics and telemetry | Agent-side buffer, batch, downsample | Drop on overflow with a counter | Freshness over completeness |
| Bulk import | COPY or multi-row insert in chunks | Staging table, deferred indexes | Throughput |
| One celebrity key | Salting or sharding | Top-K detection | Partition ceiling |
| Multi-tenant SaaS | Partition by tenant | Hash-tag keys, affinity routing | Locality, isolation |
| Search-index updates | Batch with a flush interval | Coalesce by document id | Index refresh cost |
| Cache plus database | Write-behind with coalescing | Dirty-age metric | Hot keys written often |
Trade-offs
| Technique | Latency | Durability | Consistency | Complexity |
|---|---|---|---|---|
| Direct write | Highest per event | Strongest | Strongest | Lowest |
| In-memory buffer | Lowest | Weakest | Stale by interval | Low |
| Durable queue buffer | Low | Strong | Stale by consumer lag | Medium |
| Batching | Adds up to linger | Same as target | Stale by linger | Low |
| Coalescing | Adds up to flush interval | Loses intermediates | Final value only | Medium |
| Sharded counter | Lower write, higher read | Same as store | Sum is not a snapshot | Medium |
| Key salting | Lower write, higher read | Same as store | Reads merge | Medium |
| Approximate | Lowest | n/a | Error bound | Low to medium |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel or Go monolith with PostgreSQL. Start with a per-process buffer: a coalesce.Deltas map flushed every few seconds plus a drain on SIGTERM, or Cache::increment with a scheduled flush. One database, so a plain upsert is enough; add the dedup table only when a source can replay. Measure first: if the hot row is not a problem, do not buffer.
Modular monolith: boundaries without the network
Each module owns its tables; a "metrics" module owns page_counters and exposes Views::record(pageId). Modules do not update each other's counters row by row; they call the owner, which buffers and flushes. Keep the buffer inside the owning module so the durability window is one module's concern.
Microservices: every arrow is a decision
The product service emits PageViewed {event_id, page_id} to Kafka; the analytics service consumes batches and writes with ON CONFLICT (event_id) DO NOTHING. At-least-once delivery plus the dedup key gives an effectively-once count (Delivery Guarantees, Idempotent Consumers & the Inbox). Producer settings (linger.ms, batch.size, acks=all, idempotence) set the producer-side window; consumer commit after the database commit sets the consumer-side window. Key by page_id if per-page order matters; salt if one page dominates.
Distributed data: replicas, caches, regions
Counters on replicated stores: a sharded counter on one Redis primary is exact but a failover can lose the last second (asynchronous replication, see Replication, Read Replicas & Failover). Across regions use per-region counters and sum (a grow-only counter, one of the CRDTs), which avoids cross-region write latency. Reads from replicas add lag to the staleness bound. Firestore, DynamoDB and Cassandra already distribute counters or partitions: salt keys to avoid per-partition ceilings.
Scaling path: 1x, 10x, 100x
| Load | Design | What changes |
|---|---|---|
| 1x: hundreds of writes/s | Direct UPDATE or increment | Nothing; do not optimise yet |
| 10x: thousands/s | Per-process coalescing, flush each 1–5 s; multi-row inserts | Add the loss window to the SLO |
| 100x: tens of thousands/s | Redis shards or Kafka, batch consumers, time-partitioned tables, HyperLogLog for uniques | Several flushers, dedup keys, partition by key |
| 1000x: hundreds of thousands/s | Sharded database or a purpose-built store, per-region counters, downsampling | Salting for hot keys, backpressure end to end |
Lab: from per-event writes to a buffered pipeline, with numbers
Expected, not run, except the Go tests and benchmark which were run on the author's laptop. Setup uses a single PostgreSQL and a single Redis you start yourself.
CREATE TABLE page_counters (page_id text PRIMARY KEY, views bigint NOT NULL DEFAULT 0);
CREATE TABLE page_events (event_id text PRIMARY KEY, page_id text NOT NULL, views int NOT NULL DEFAULT 1,
created_at timestamptz NOT NULL DEFAULT now());
INSERT INTO page_counters VALUES ('p7', 0);- Hot row baseline. Two terminals run
pgbench -n -c 32 -T 30 -f hot.sqlwithhot.sqlcontainingUPDATE page_counters SET views = views + 1 WHERE page_id = 'p7';. Expected: throughput limited by the row lock;SELECT * FROM pg_locks WHERE NOT grantedshows many waiters; the result is a few thousand TPS at best. - Sharded rows. Create
counter_shardsfrom the Sharded counters block, changehot.sqlto pick:shard = random(0,15)with\set shard random(0,15), and re-run. Expected: throughput rises with the shard count until CPU or WAL flush becomes the limit; reads need theSUMquery. - Batch inserts. Compare 100,000 single-row inserts (one commit each) against the Go
ingestdflush shape (500 rows per statement). Expected: an order of magnitude or more fewer commits; the exact speed-up depends onsynchronous_commitand the disk. - Crash test. Run the Go flusher,
kill -9it mid-run, restart, and compareSELECT sum(views)with the number of events sent. Expected: withCloseskipped you lose the in-memory queue; with the Redis list plusinsertOrIgnoreand trim-after-commit nothing is lost and a replay changes nothing. - Graceful drain. Send
SIGTERM, expectingestdto print one final flush and exit with status 0 within the drain timeout. - In-process measurement that was run:
go test -race -count=1 ./...passed indocs/snippets/system-design/write-buffering-sharded-counters/go, andgo test -bench . -run xxx ./counterprinted 60.9 ns/op for one shard and 14.6 ns/op for sixteen on a 12-CPU Apple Silicon laptop (single run, illustrative).
Common misconceptions
| Belief | Reality |
|---|---|
| "Buffering makes the database faster." | It makes the caller faster; the database is faster only if you also batch or coalesce |
| "A queue in front of the database means no data loss." | Only if the queue is durable and you acknowledge after it is |
| "A bigger batch is always better." | Past the fixed-cost knee it only adds latency and failure blast radius |
"ON CONFLICT DO UPDATE is idempotent." | It is atomic; x = x + 1 repeated adds twice |
| "Hashing prevents hot partitions." | It spreads different keys, not one hot key |
| "A sharded counter is approximate." | It is exact once writes land; reads are not a snapshot |
| "Redis pipelining is a transaction." | It only saves round trips; use MULTI/EXEC for atomicity |
| "Eventual consistency has no bound." | You can enforce and alert on a flush interval |
| "More shards is always better." | Reads cost N keys and storage grows; size N from the target rate |
| "Time is a good partition key." | A raw time key makes the newest partition the hot one |
| "Cache::increment works with any cache store." | It is atomic only on stores with an atomic increment; file and array are not |
Cheat sheet
| Topic | What to remember |
|---|---|
| Buffer | Fast ack, then drain; bound the queue and decide full means block, shed or spill |
| Durability window | Say it as a number; shorten it with a durable log, acks=all or appendfsync always |
| Batch | Flush on size or time, whichever first; hundreds to thousands of rows per statement |
COPY | Fastest bulk load into PostgreSQL; one transaction per chunk |
| Parameter limit | 65,535 bind parameters per PostgreSQL statement |
| Kafka | linger.ms 5 and batch.size 16384 are defaults; acks=all plus idempotence for safety |
| Redis | Pipeline in chunks of about 10k; INCRBY is atomic; hash tags keep keys in one slot |
| Coalesce | Add for deltas, highest version for absolute values; swap the map on flush |
| Sharded counter | Random shard on write, sum on read; N from rate divided by per-shard rate |
| Idempotency | Dedup key under a unique constraint, or absolute values; deduplicate within a batch |
| Ordering | Per key only; route by key; sort keys inside a batch |
| Locality | Partition key from the access pattern; hash tags, affinity routing, clustering |
| Hot key | Salt it or shard it; reads merge all salts |
| Approximate | HyperLogLog 12 KB, 0.81% error; exact for money |
| Shutdown | Drain on SIGTERM with a deadline; never cancel the final flush |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A service acknowledges a write as soon as it is appended to an in-memory queue. State the durability window and one way to shorten it. Must-know
Answer
Answer: The window is everything not yet flushed: a crash loses it, up to the flush interval plus queue depth. Shorten it by flushing more often, by putting a durable log (Kafka with acks=all, a database queue table, or a WAL-first design) before the acknowledgement, or by moving the buffer to Redis with appendfsync always.
2 — Why does a bigger batch stop helping? Important
Answer
Answer: The per-row cost is F / B + r; once F / B is small compared with r the cost is flat, while latency, memory and the amount one failure rolls back keep growing with B.
3 — Batching and coalescing both reduce database messages. What is the difference? Must-know
Answer
Answer: Batching sends the same changes in fewer messages; coalescing sends fewer changes by merging writes to the same key (summing deltas or keeping the latest version).
4 — A counter uses ON CONFLICT DO UPDATE SET views = page_counters.views + EXCLUDED.views. Is a retried batch safe? Must-know
Answer
Answer: No. The statement is atomic but not idempotent; a second run adds the deltas again. Record event ids under a unique constraint in the same transaction and apply deltas only for newly inserted ids, or write absolute values.
5 — Why must a multi-row upsert be deduplicated first? Important
Answer
Answer: PostgreSQL raises a cardinality violation (SQLSTATE 21000, "ON CONFLICT DO UPDATE command cannot affect row a second time") when one command would affect the same row twice.
6 — Design a sharded counter for 20,000 increments per second when one shard sustains about 1,000 per second. How many shards, and what does a read cost? Important
Answer
Answer: At least 20 shards, 32 for headroom. A read sums N rows or keys (one MGET in Redis, one SUM in SQL); keep a periodic rollup if reads are frequent.
7 — Why does hashing not protect against a hot partition, and what does? Must-know
Answer
Answer: Hashing spreads distinct keys; one key hashes to one partition. Salt the key with a random or calculated suffix (writes pick any, reads query all) or shard it into sub-keys.
8 — Why use a Redis hash tag in cnt:{p7}:3? Important
Answer
Answer: In Redis Cluster only keys with the same hash slot can be used in one multi-key command or pipeline group; the part in braces decides the slot, so all shards of one counter share it. The cost is that one counter lives on one cluster node.
9 — What must Close do in a batcher, and what must it not do? Important
Answer
Answer: Stop intake, flush everything queued including the partial batch, and wait for the last flush within a deadline. It must not cancel the final flush with the shutdown context.
10 — When is write buffering the wrong tool? Must-know
Answer
Answer: For data whose loss window must be zero or whose reads must see the write immediately: payments, balances, stock reservation. Use an atomic transactional write, a ledger and an outbox instead.
Glossary
| Term | Meaning |
|---|---|
| Write buffering | Acknowledging a write into a fast buffer and applying it to the database later |
| Batching | Sending many writes in one operation |
| Flush | Writing the buffered items out to the destination |
| Batch size | Maximum items or bytes per flush |
| Linger | Maximum time a partial batch waits before it is flushed (linger.ms in Kafka) |
| Pipelining | Sending several commands without waiting for each reply (Redis) |
| Bulk insert | Loading many rows with one statement or command |
| Multi-row INSERT | One INSERT with several VALUES tuples |
| COPY | PostgreSQL bulk load and export command |
| Upsert | Insert, or update if the key exists (INSERT ... ON CONFLICT DO UPDATE) |
| ON CONFLICT | PostgreSQL clause that handles unique-key conflicts |
| Write-behind | Acknowledge after the cache write, flush to the database later |
| Coalescing | Merging several pending writes to one key into one |
| Last-writer-wins | Keep the write with the highest version or timestamp |
| Delta | An increment or decrement rather than an absolute value |
| Durability window | Time during which an acknowledged write exists only in volatile state |
| Acknowledgement | The reply that tells a client its write was accepted |
| Crash loss | Data lost because a process died before flushing |
| WAL | Write-ahead log: the database's durable record of changes |
| Sharded counter | One logical counter stored as N sub-counters |
| Hot row | A single row updated by many transactions at once |
| Contention | Waiting caused by many writers needing the same resource |
| Row lock | Lock held on a row until the transaction ends |
| Sub-counter | One of the N parts of a sharded counter |
| Random shard | Picking the sub-counter at random for each write |
| Sum on read | Computing the total by adding all sub-counters when reading |
| INCRBY | Redis command that atomically adds an integer to a key |
| Approximate counter | A counter with a stated error bound |
| HyperLogLog | Probabilistic structure for distinct counts (Redis PFADD, PFCOUNT) |
| Distinct count | Number of unique elements in a set |
| Bounded staleness | A guarantee that reads are at most a stated age behind |
| Idempotent batch | A batch that can be applied repeatedly with the same result |
| Dedup key | Unique id used to detect an item already applied |
| Per-key ordering | Writes to one key are applied in production order |
| Data locality | Storing data that is used together in one place |
| Co-location | Putting related entities on the same shard or node |
| Partition key | The field whose hash or range decides the partition |
| Affinity routing | Sending requests for the same entity to the same worker |
| Cache locality | Keeping hot data in the CPU cache or a nearby cache |
| False sharing | Cores contending for one cache line holding independent variables |
| Hot partition | A partition that receives disproportionate traffic |
| Key salting | Adding a random suffix to a key to spread it over partitions |
| Time bucketing | Grouping rows into time slices (hour, day) |
| Append-only | Data is added, never updated in place |
| Downsampling | Replacing detailed old data with coarse aggregates |
| View counter | A counter of page or video views |
| Like counter | A counter of likes, usually with per-user dedup |
| Analytics ingest | High-volume intake of events for later aggregation |
| Backpressure | Slowing or refusing producers when a buffer is full |
| Graceful drain | Flushing queued items before shutting down |
Redis::pipeline | Laravel facade method that batches Redis commands |
Cache::increment | Laravel atomic increment on a cache store |
upsert() | Laravel query-builder method for multi-row upserts |
Bus::batch | Laravel job batching |
References
All URLs returned HTTP 200 when fetched; saved copies are listed in the chapter handoff.
- PostgreSQL, COPY, INSERT, Populating a Database, Asynchronous Commit, Explicit Locking, Message Formats
- Redis, Pipelining, INCRBY, HyperLogLog, PFADD
- Apache Kafka, documentation and ProducerConfig source
- Firebase, Distributed counters
- Amazon DynamoDB, Partition key design, Write sharding, Burst and adaptive capacity
- Martin Kleppmann, Designing Data-Intensive Applications
- Laravel 13, Query Builder, Redis, Cache, Queues, Task Scheduling
- Go, sync, sync/atomic; go-redis, Pipelines