Skip to content

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 forGo to
The whole page in three tablesEverything in one minute
Why one write per event does not scaleWhy it exists
Sources: PostgreSQL, Redis, Kafka, Firestore, DynamoDBWhere it comes from
Keeping writes in memory or a queue before the databaseWrite buffering, Durability window
Size versus latency, COPY, multi-row INSERT, pipeliningBatching
Collapsing many updates into oneCoalescing, Write-behind
One row everybody updatesSharded counters
Approximate and distinct countsApproximate counters and HyperLogLog
How stale is allowedBounded staleness
Retries and duplicate batchesIdempotent batch writes
Order inside a batchOrdering
Keeping related data togetherData locality, Cache locality
One celebrity keyHot partitions and key salting
Metrics and events over timeTime-series writes
Knobs, limits and error messagesMechanics
CodeGo, Laravel
View counter, like counter, analytics ingest, importsSolving the classic problems
Which technique for which workloadChoosing
Monolith to distributed systemIn architecture
Numbers and failure drillsLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The five moves.

MoveIn plain wordsTiny exampleWhat it buysWhat it costs
BufferHold the write somewhere cheap and acknowledge nowAppend the event to an in-memory queue or a Redis listLow latency, absorbs spikesA window where data exists only in the buffer
BatchSend many writes in one round tripOne multi-row INSERT, one COPY, one Redis pipelineFewer round trips, commits and syscallsAdded latency up to the flush interval
CoalesceMerge writes to the same key before sending1,000 views + 1 become one views + 1000Fewer rows touched, less lock timeIntermediate values are never visible
ShardSplit one hot key into N sub-keysCounter row becomes 16 rows, pick one at randomWrite throughput grows with NReads must sum N values
Co-locatePut data that is used together in one placePartition by user_id so one user's rows share a shardOne write or query touches one nodeSkew 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.

ContractThe questionTypical answer for a view counterTypical answer for a payment
Durability windowHow much acknowledged data may a crash lose?Up to the last flush (seconds)None: write-ahead, then acknowledge
Staleness boundHow old may a read be?Flush interval plus replica lagRead your own write
AccuracyMust the number be exact?Approximate is fine for display; exact in the ledgerExact
OrderingWhich order must be preserved?None, increments commutePer account, strictly
DuplicatesWhat if a batch is applied twice?Dedup key or absolute valuesIdempotency key mandatory

Numbers to keep in your head. All are either from the cited documentation or marked as a back-of-envelope estimate.

FactValueSource
Redis round trip over a slow Internet link250 ms RTT caps one client at 4 requests per second, whatever the server can doRedis pipelining docs
Redis pipeline batch the docs suggestAround 10,000 commands, then read repliesRedis pipelining docs
Kafka producer defaultslinger.ms 5 (since Kafka 4.0, it was 0), batch.size 16384 bytesKafka ProducerConfig
PostgreSQL asynchronous commit risk windowAt most three times wal_writer_delayPostgreSQL docs, section 28.4
Firestore counter shardOne sustained increment per second per shard document; 10 shards give 10xFirebase docs
DynamoDB single partition ceiling3,000 RCU and 1,000 WCU for one item keyDynamoDB docs
Single hot row (estimate, not a measurement)If the row lock is held 1 ms, about 1,000 updates per second per rowBack-of-envelope
HyperLogLog in RedisUp to 12 KB, standard error 0.81%Redis docs
writer 1writer 2writer 3bounded queue (in memory)Add blocks or TryAdd returns ErrFullflush when MaxBatch itemsor Linger elapsedflusherone batchdatabase1 round tripcrash loss window: everything in this box is gone on kill -9Ack to the client happens here, before the database has the data

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 techniquesWith them
One round trip and one commit per eventOne round trip and one commit per batch
N updates to one key take N lock turnsOne update with the sum, or N shards in parallel
A traffic spike goes straight to the databaseThe spike lands in a buffer and drains at the database's pace
Hot keys cap total throughputHot keys spread over many rows or partitions
Latency follows the slowest commitLatency follows an in-memory append
Simple, exact, durable at the moment of the responseFast 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 ​

  1. "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".
  2. "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.
  3. "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).

SourceWhat it statesWhy 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 twiceThe primitive under idempotent batch upserts and why a batch must be deduplicated
Redis docs, PipeliningThe 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 ProducerConfiglinger.ms "can be thought of as analogous to Nagle's algorithm in TCP"; default changed from 0 to 5 in Kafka 4.0Size-or-time flushing is the standard producer design
Firebase docs, Distributed countersA 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 capacityA single item key can reach at most 3,000 RCUs and 1,000 WCUs of one partitionWhy 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 spotsThe 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.

text
     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 0

Real 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 locationSurvives process crashSurvives machine lossShared by many app serversTypical use
In-process memory (channel, array)NoNoNoCheap metrics, best-effort events
Local disk spool (file, SQLite)YesNoNoAgents and edge collectors
Redis list or stream (default persistence)Depends on appendonly and appendfsyncWith replication, mostlyYesCounters, small event streams
Kafka topic (acks=all, replicated)YesYesYesAnalytics ingest, event backbone
Database queue tableYesAs durable as the databaseYesWhen 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".

text
     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 restart

Real 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:

ProductSettingWhat "acknowledged" meansLoss on crash
PostgreSQLsynchronous_commit = on (default)WAL flushed to disk before the answerNone for committed transactions
PostgreSQLsynchronous_commit = offAnswer before the WAL flush; WAL writer flushes in the backgroundUp to about three times wal_writer_delay; the database stays consistent
Kafka produceracks=0Not waited forPossible without notice
Kafka produceracks=1Partition leader has appendedLost if the leader dies before replication
Kafka produceracks=allAll in-sync replicas have appendedNone while min.insync.replicas holds
Redisappendonly yes, appendfsync everysecCommand executed in memory; fsync about once a secondAbout one second of writes
Redisappendfsync alwaysfsync before replyingNone, at a large throughput cost
Application bufferAck on enqueueItem is in process memoryEverything 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).

sql
-- 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 crash

Batching 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).

text
     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 commit

Real scenario: log shipping, metrics collectors, bulk CSV imports, event ingest, ORM insert() of arrays, Kafka producers, Redis pipelines.

How each product batches:

ProductMechanismFlush triggerKnob
PostgreSQLCOPY ... FROMOne command streams all rowsCOPY options; wrap in one transaction
PostgreSQLMulti-row INSERT ... VALUES (...), (...)One statementBind-parameter limit of 65,535 (Int16 count in the protocol Bind message)
MySQL / InnoDBMulti-row INSERT, LOAD DATAOne statementmax_allowed_packet
Kafka producerRecord batches per partitionbatch.size bytes full, or linger.ms elapsedbatch.size 16384, linger.ms 5, compression.type
RedisPipelineClient sends many commands before reading repliesChunk of about 10k commands
RedisMSET, HSET with many fields, PFADD with many elementsOne commandCommand argument size
LaravelDB::table()->insert([...]), upsert(), Redis::pipeline(), Bus::batch()One callChunk with array_chunk
Go database/sqlpgx.CopyFrom, pgx.Batch, hand-built multi-row statementOne callYour 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.

sql
-- 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).

text
     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:

DataMerge ruleSafe to coalesce?Condition
Counter incrementsAdd the deltasYesThe consumer only needs the sum
Last-seen timestamp, current statusKeep the highest version or timestampYesVersion or clock must be trustworthy
Append-only eventsNone; every event mattersNoDedupe by id only
Balance with a CHECK constraintAdd the deltasCarefulEach intermediate state may have mattered; keep a ledger
Set membership (add, remove)Last operation per element winsYesNeeds 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.

text
     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.

ProductWrite-behind supportNotes
RedisPattern only (your code flushes)Persistence (appendonly) protects the buffer, not the database sync
Hibernate / JPAWrite-behind through the session flushTransaction-scoped, not cross-request
LaravelPattern only: Cache::increment or Redis plus a scheduled flushSee Laravel
Hazelcast, Apache IgniteBuilt-in write-behind with coalescing optionsCheck 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.

text
     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:

ProductCounter facilitySharding approachLimit
PostgreSQLUPDATE ... SET n = n + 1Table of (counter_id, shard, n), random shard on write, SUM on readRow lock per shard; MVCC leaves a dead tuple per update, so keep it VACUUM-friendly
MySQL / InnoDBSameSameRow lock per shard; gap locks are not involved on a primary-key update
RedisINCRBY key n, 64-bit signed integersN keys with a hash tag cnt:{id}:0..N-1, MGET to sumA single key is one thread's serial work; a Redis Cluster key lives on one shard (slot)
DynamoDBUpdateItem with ADDRandom suffix on the partition key, Query all suffixes1,000 WCU per partition key
FirestoreTransaction or FieldValue.incrementSubcollection of shard documentsAbout one sustained write per second per document
CassandraCounter columnsCounter columns are distributed by design; contention is on the partitionCounters are not idempotent on retry
Go (in process)atomic.Int64Padded array of atomics, random indexFalse 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.

sql
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';
text
$ 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 values
One hot rowN sub-counterswriterwriterwriterviewsrow lockwrites serialise:~1 / lock hold timewriterwriterwritershard 0shard 1shard 2shard N-1sumon readwrite: INCRBY a random shard read: MGET all shards, add upthroughput scales with N, reads cost N keys

The 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%".

text
     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 approximate

Real scenario: unique visitors per page per day; distinct search queries; "N people are viewing"; approximate like counts shown as "1.2M".

TechniqueAnswersErrorMemoryMergeable
Exact set (SADD, SCARD)Distinct count, membershipNoneGrows with NYes
HyperLogLog (PFADD, PFCOUNT, PFMERGE)Distinct countStandard error 0.81% in RedisUp to 12 KB per keyYes
Count-Min SketchFrequency of an itemOvercount bounded by widthFixedYes (add)
Sampling (1 in k)TotalsGrows as the rate fallsTinyYes
Sharded exact counterTotalNone after all writes landN rowsYes

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.

text
     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 s

Real 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 fromTypical sizeHow to shorten it
Buffer flush interval1–60 sSmaller Linger, or flush on size
Queue wait under loadGrows with backlogMore flushers, bigger batches
Replica lagMilliseconds to secondsRead from the primary for the writer
Cache TTLSeconds to minutesLower 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.

text
     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 deltas

Real 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.

TechniqueIdempotent?CostWhen
Upsert of absolute values (upsert())YesNoneRollups, snapshots, last-writer-wins
Delta plus dedup table in one transactionYesOne extra insert per eventCounters from at-least-once sources
Offset or sequence stored with the resultYesOne rowSingle-partition streams
Delta aloneNoNoneNever, unless loss is acceptable
Idempotency key per batchYes, per batchOne row per batchBulk API endpoints

Fix / how to use it:

sql
-- 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.

text
     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.

LayerOrdering guaranteeHow to keep it
In-process channel, one consumerArrival orderOne flusher goroutine, as in the Go batcher
Kafka partitionOrder within a partitionKey = entity id; max.in.flight.requests.per.connection of 5 or less with idempotence enabled
RabbitMQ queue with one consumerOrder, until a requeueSingle active consumer
Redis listFIFOSingle drain
Parallel flush workersNone across batchesRoute by key hash to a fixed worker
Multi-row upsertNone between rows of one statementDo 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.

text
     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.

LayerLocality toolProduct exampleEffect
Shard or partitionPartition keyCitus distribution column, DynamoDB partition key, Cassandra partition key, Kafka message keyOne node serves a whole entity
Disk pageClustering key, CLUSTER, INCLUDE, InnoDB primary keyInnoDB clustered index stores rows in primary-key orderRange scans read adjacent pages
LSM engineKey prefix, column familiesRocksDB prefix extractor; Cassandra clustering columnsA write goes to one memtable and a scan reads one run; see Storage Engines
CacheHash tagRedis Cluster {id} forces one slotMulti-key commands and pipelines stay legal
Request routingAffinity routingConsistent hashing, sticky sessions, Kafka consumer assignmentSame entity, same process, warm cache
CPUNUMA, cache linesPer-core counters, paddingFewer 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.

text
     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 bounce

Real 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.

LayoutCost per Add (16 goroutines, this chapter's benchmark)Notes
1 padded shard60.9 nsEvery core contends for one line
16 padded shards14.6 nsCores 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.

text
     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, merge

Real 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).

StoreHot-key symptomMitigation
DynamoDBProvisionedThroughputExceededException, throttling on one partition keyRandom or calculated suffix (write sharding); on-demand mode does not remove the partition ceiling
CassandraOne node at 100% CPU, WriteTimeoutExceptionAdd a bucket to the partition key
KafkaOne partition lagging while others idleSalt the key (loses per-key order), or a custom partitioner
Redis ClusterOne node hot, one slot ownerShard the key across hash tags that map to different slots
PostgreSQLLock waits on one row; pg_locks shows many waitersSharded counter rows or batching
HBase / BigtableOne region server hot on a monotonically increasing keyReverse 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.

No salt: key = video:42Salted: key = video:42#0..3video:42celebrity keypartition A: hotpartition Bpartition Cpartition Dvideo:42+ random 0..3#0 partition A#1 partition B#2 partition C#3 partition Dpartition limit caps the whole keyreads must query every salt and merge

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.

text
     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 years

Real scenario: metrics (Prometheus blocks, InfluxDB, TimescaleDB hypertables), analytics events, IoT telemetry, audit trails, order events.

PatternWhat it doesExample
Append-onlyNever update a row; add a new oneLSM engines write sequentially, see Storage Engines
Time bucket in the key(device_id, day) as partition keyCassandra and DynamoDB time-series models
Partitioned tablesOne table partition per day or monthPostgreSQL declarative partitioning; dropping a partition is instant
HypertableAutomatic time chunksTimescaleDB
DownsamplingRoll up old data, delete rawPrometheus recording rules, InfluxDB tasks
Batch by device or seriesGroup rows of one series in one writeKeeps 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.

sql
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):

BCost per rowRows per second per connectionAdded latency at 5,000 events/s
11,020 microsecondsabout 9800
10120 microsecondsabout 8,300up to 2 ms
10030 microsecondsabout 33,000up to 20 ms
1,00021 microsecondsabout 48,000up to 200 ms
10,00020.1 microsecondsabout 50,000up 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 ​

ProductKnobDefault or typicalWhat it does
Kafka producerlinger.ms5 (0 before Kafka 4.0)Wait up to this long for a partition batch to fill
Kafka producerbatch.size16384 bytesPer-partition batch size; "A small batch size will make batching less common and may reduce throughput"
Kafka producercompression.typenoneCompress whole batches; larger batches compress better
Kafka produceracks, enable.idempotenceall, true (recent clients)Durability and duplicate suppression on retry
PostgreSQLsynchronous_commitonoff trades up to three times wal_writer_delay for latency
PostgreSQLwal_writer_delay200 msInterval of the background WAL flush
PostgreSQLmax_wal_size, maintenance_work_memserver defaultsThe Populating a Database guide advises raising both for bulk loads
PostgreSQLBind parameters per statement65,535Int16 parameter count in the protocol Bind message; 3 columns means at most 21,845 rows per multi-row INSERT
RedisPipeline sizeabout 10,000 commandsReplies are queued in server memory until read
RedisappendfsynceverysecDurability of buffered counters
LaravelSchedule::command(...)->everyTenSeconds()n/aThe staleness bound of a flushed counter
Laravelupsert() chunkingyour array_chunk sizeKeeps statements below parameter and packet limits
DynamoDBPer-partition throughput3,000 RCU and 1,000 WCUCeiling for a single item key

What goes wrong, verbatim ​

WhereMessage or symptomMeaningWhat to do
PostgreSQLON CONFLICT DO UPDATE command cannot affect row a second time (SQLSTATE 21000)The batch contains the same key twiceDeduplicate or coalesce before the statement
PostgreSQLdeadlock detected (40P01)Two flushers updated the same rows in different orderSort keys; retry the batch
PostgreSQL driversA driver-side error about more than 65535 parameters (wording varies by driver)Too many bind parameters in one statementChunk the batch
RedisWRONGTYPE Operation against a key holding the wrong kind of valueA shard key was written with another typeNamespace keys; do not reuse
RedisERR increment or decrement would overflow64-bit signed limit reachedRotate the counter or flush and reset
Redis ClusterCROSSSLOT Keys in request don't hash to the same slotA multi-key command spans slotsUse a hash tag (cnt:{p7}:3)
KafkaRecordTooLargeExceptionOne record above max.request.sizeSplit or compress the record
KafkaTimeoutException after delivery.timeout.ms (120 s default)The batch could not be delivered in timeHandle the callback; the batch is not retried further
DynamoDBProvisionedThroughputExceededExceptionA partition ceiling was exceededSalt the key; back off
Gobatcher: queue full (ErrFull)Bounded buffer reached its limitShed, block with a deadline, or spill
LaravelIlluminate\Database\QueryException with SQLSTATE 22P02 or 23505Bad value, or duplicate key in a plain insertUse 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 ​

text
     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 flush

Go ​

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.

go
// 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:

go
// 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):

go
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:

go
// 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
}
go
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:

go
// 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)
}
go
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:

go
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
}
go
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:

go
// 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
}
go
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)
	}
}
go
// 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 select with default gives TryAdd. Closing the channel after setting a flag under a sync.RWMutex is what makes Close race-free (verified with go test -race).
  • sync/atomic types (atomic.Int64) are lock-free counters; a sync.Mutex around 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.Reset needs the stop-and-drain idiom (see resetTimer) 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/sql has no multi-row API; build the statement yourself (as ingest does) or use pgx (CopyFrom for the COPY protocol, pgx.Batch to send several statements in one round trip). Keep every statement below the 65,535 parameter limit.
  • go-redis Pipeline() and TxPipeline() both batch commands; the second wraps them in MULTI/EXEC. A ClusterClient groups pipelined commands by node, but a multi-key command such as MGET still needs a shared slot, which the hash tag in ShardKey provides.
  • math/rand/v2 top-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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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
<?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 to INSERT ... ON CONFLICT ... DO UPDATE on PostgreSQL. The Laravel docs state that all databases except SQL Server require the unique-by columns to have a primary or unique index. The $update array 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 in FlushViewCounts.
  • insertOrIgnore skips 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 (use Redis::transaction for MULTI/EXEC).
  • Cache::increment('key', $amount) is atomic only on stores that implement atomic increments (Redis, Memcached, database with a locking statement); the file and array stores are not safe across processes.
  • Bus::batch([...])->allowFailures()->dispatch() is job-level batching: it gives progress, cancellation and then/catch/finally callbacks, but it is not a database batch. Put the multi-row statement inside each job. It needs the job_batches table (php artisan make:queue-batches-table).
  • Schedule::command('views:flush')->everyTenSeconds()->withoutOverlapping()->onOneServer(): sub-minute scheduling needs schedule:run to run every minute (Laravel then loops for the minute) or schedule:work; onOneServer needs 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.

SolutionHowAdvantageCost or limit
Buffer in Redis, flush every few secondsINCRBY per view, scheduled upsert that adds the deltaDatabase sees one write per page per intervalLoses up to one interval plus unflushed Redis data on a crash
Sharded Redis counterN shard keys, sum on readRemoves the hot key inside RedisRead costs N keys
In-process coalescingcoalesce.Deltas per app server, flush each 1–5 sNo Redis round trip per viewLoss window equals process crash; N servers make N writers
Append events, aggregate laterInsert events in batches, GROUP BY in a jobNothing is lost silently, can recomputeStorage grows; hourly latency
ApproximateSample 1 in k, or HyperLogLog for distinctTiny stateShown 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.

SolutionHowAdvantageCost or limit
Source of truth is a setTable likes (post_id, user_id) with a unique keyDedup is a constraint; the count can always be recomputedA write per like; hot post still hot
Counter beside the setInsert into likes ON CONFLICT DO NOTHING RETURNING, add 1 only if inserted, same transactionExact and idempotentOne extra row update; shard it for celebrities
Sharded counter for hot postsCounter rows by (post_id, shard)Spreads the lockSum on read, rare
Cached count with rebuildRedis INCR, nightly recompute from likesFast display; self-healingTemporary drift

Analytics ingest ​

Symptom: ten thousand events per second and a database at 100% CPU doing single-row inserts.

SolutionHowAdvantageCost or limit
Kafka in frontProducer with linger.ms and batch.size, consumer inserts in batchesDurable buffer, replay, backpressure by lagAnother system to run
Batched INSERT with ON CONFLICT DO NOTHINGingest.BuildEventInsertIdempotent, simpleNeeds an event id
COPY into a staging table, then INSERT ... SELECT ... ON CONFLICTFastest load, then mergeBest throughputTwo steps; staging cleanup
Time-partitioned tableOne partition per dayCheap retention, small indexesPartition management

The flusher crashed ​

Symptom: the process died between taking items from the buffer and committing them.

Where the crash fellResultFix
Before taking itemsNothing lost if the buffer is durableNone
After take, before commitItems lost if the take deleted themTrim the buffer only after commit; peek, write, then trim
After commit, before trimItems applied twice on restartIdempotent write (dedup key or absolute value)
During graceful shutdownPartial batch lost if the drain is skippedClose(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 ​

WorkloadRecommendedExtra techniqueReason
Page views, impressionsRedis shards, flush every 5–10 sDisplay db + pending; HLL for uniquesLoss of seconds is acceptable
Likes, votesSet table plus counter in one transactionShard counters for hot postsExactness and dedup matter
Click and analytics eventsKafka or a Redis list, batched insertTime partitions, rollupsDurable replayable buffer
Money, stock, balancesNo write bufferingAtomic UPDATE, ledger, outboxLoss window unacceptable
Metrics and telemetryAgent-side buffer, batch, downsampleDrop on overflow with a counterFreshness over completeness
Bulk importCOPY or multi-row insert in chunksStaging table, deferred indexesThroughput
One celebrity keySalting or shardingTop-K detectionPartition ceiling
Multi-tenant SaaSPartition by tenantHash-tag keys, affinity routingLocality, isolation
Search-index updatesBatch with a flush intervalCoalesce by document idIndex refresh cost
Cache plus databaseWrite-behind with coalescingDirty-age metricHot keys written often

Trade-offs ​

TechniqueLatencyDurabilityConsistencyComplexity
Direct writeHighest per eventStrongestStrongestLowest
In-memory bufferLowestWeakestStale by intervalLow
Durable queue bufferLowStrongStale by consumer lagMedium
BatchingAdds up to lingerSame as targetStale by lingerLow
CoalescingAdds up to flush intervalLoses intermediatesFinal value onlyMedium
Sharded counterLower write, higher readSame as storeSum is not a snapshotMedium
Key saltingLower write, higher readSame as storeReads mergeMedium
ApproximateLowestn/aError boundLow 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 ​

LoadDesignWhat changes
1x: hundreds of writes/sDirect UPDATE or incrementNothing; do not optimise yet
10x: thousands/sPer-process coalescing, flush each 1–5 s; multi-row insertsAdd the loss window to the SLO
100x: tens of thousands/sRedis shards or Kafka, batch consumers, time-partitioned tables, HyperLogLog for uniquesSeveral flushers, dedup keys, partition by key
1000x: hundreds of thousands/sSharded database or a purpose-built store, per-region counters, downsamplingSalting 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.

sql
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);
  1. Hot row baseline. Two terminals run pgbench -n -c 32 -T 30 -f hot.sql with hot.sql containing UPDATE page_counters SET views = views + 1 WHERE page_id = 'p7';. Expected: throughput limited by the row lock; SELECT * FROM pg_locks WHERE NOT granted shows many waiters; the result is a few thousand TPS at best.
  2. Sharded rows. Create counter_shards from the Sharded counters block, change hot.sql to 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 the SUM query.
  3. Batch inserts. Compare 100,000 single-row inserts (one commit each) against the Go ingestd flush shape (500 rows per statement). Expected: an order of magnitude or more fewer commits; the exact speed-up depends on synchronous_commit and the disk.
  4. Crash test. Run the Go flusher, kill -9 it mid-run, restart, and compare SELECT sum(views) with the number of events sent. Expected: with Close skipped you lose the in-memory queue; with the Redis list plus insertOrIgnore and trim-after-commit nothing is lost and a replay changes nothing.
  5. Graceful drain. Send SIGTERM, expect ingestd to print one final flush and exit with status 0 within the drain timeout.
  6. In-process measurement that was run: go test -race -count=1 ./... passed in docs/snippets/system-design/write-buffering-sharded-counters/go, and go test -bench . -run xxx ./counter printed 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 ​

BeliefReality
"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 ​

TopicWhat to remember
BufferFast ack, then drain; bound the queue and decide full means block, shed or spill
Durability windowSay it as a number; shorten it with a durable log, acks=all or appendfsync always
BatchFlush on size or time, whichever first; hundreds to thousands of rows per statement
COPYFastest bulk load into PostgreSQL; one transaction per chunk
Parameter limit65,535 bind parameters per PostgreSQL statement
Kafkalinger.ms 5 and batch.size 16384 are defaults; acks=all plus idempotence for safety
RedisPipeline in chunks of about 10k; INCRBY is atomic; hash tags keep keys in one slot
CoalesceAdd for deltas, highest version for absolute values; swap the map on flush
Sharded counterRandom shard on write, sum on read; N from rate divided by per-shard rate
IdempotencyDedup key under a unique constraint, or absolute values; deduplicate within a batch
OrderingPer key only; route by key; sort keys inside a batch
LocalityPartition key from the access pattern; hash tags, affinity routing, clustering
Hot keySalt it or shard it; reads merge all salts
ApproximateHyperLogLog 12 KB, 0.81% error; exact for money
ShutdownDrain on SIGTERM with a deadline; never cancel the final flush

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Write bufferingAcknowledging a write into a fast buffer and applying it to the database later
BatchingSending many writes in one operation
FlushWriting the buffered items out to the destination
Batch sizeMaximum items or bytes per flush
LingerMaximum time a partial batch waits before it is flushed (linger.ms in Kafka)
PipeliningSending several commands without waiting for each reply (Redis)
Bulk insertLoading many rows with one statement or command
Multi-row INSERTOne INSERT with several VALUES tuples
COPYPostgreSQL bulk load and export command
UpsertInsert, or update if the key exists (INSERT ... ON CONFLICT DO UPDATE)
ON CONFLICTPostgreSQL clause that handles unique-key conflicts
Write-behindAcknowledge after the cache write, flush to the database later
CoalescingMerging several pending writes to one key into one
Last-writer-winsKeep the write with the highest version or timestamp
DeltaAn increment or decrement rather than an absolute value
Durability windowTime during which an acknowledged write exists only in volatile state
AcknowledgementThe reply that tells a client its write was accepted
Crash lossData lost because a process died before flushing
WALWrite-ahead log: the database's durable record of changes
Sharded counterOne logical counter stored as N sub-counters
Hot rowA single row updated by many transactions at once
ContentionWaiting caused by many writers needing the same resource
Row lockLock held on a row until the transaction ends
Sub-counterOne of the N parts of a sharded counter
Random shardPicking the sub-counter at random for each write
Sum on readComputing the total by adding all sub-counters when reading
INCRBYRedis command that atomically adds an integer to a key
Approximate counterA counter with a stated error bound
HyperLogLogProbabilistic structure for distinct counts (Redis PFADD, PFCOUNT)
Distinct countNumber of unique elements in a set
Bounded stalenessA guarantee that reads are at most a stated age behind
Idempotent batchA batch that can be applied repeatedly with the same result
Dedup keyUnique id used to detect an item already applied
Per-key orderingWrites to one key are applied in production order
Data localityStoring data that is used together in one place
Co-locationPutting related entities on the same shard or node
Partition keyThe field whose hash or range decides the partition
Affinity routingSending requests for the same entity to the same worker
Cache localityKeeping hot data in the CPU cache or a nearby cache
False sharingCores contending for one cache line holding independent variables
Hot partitionA partition that receives disproportionate traffic
Key saltingAdding a random suffix to a key to spread it over partitions
Time bucketingGrouping rows into time slices (hour, day)
Append-onlyData is added, never updated in place
DownsamplingReplacing detailed old data with coarse aggregates
View counterA counter of page or video views
Like counterA counter of likes, usually with per-user dedup
Analytics ingestHigh-volume intake of events for later aggregation
BackpressureSlowing or refusing producers when a buffer is full
Graceful drainFlushing queued items before shutting down
Redis::pipelineLaravel facade method that batches Redis commands
Cache::incrementLaravel atomic increment on a cache store
upsert()Laravel query-builder method for multi-row upserts
Bus::batchLaravel job batching

References ​

All URLs returned HTTP 200 when fetched; saved copies are listed in the chapter handoff.

Built by Morteza Negahi