Sub topic 3
Central counters and auto-increment: simple, but a bottleneck
This chapter assumes you know Python, relational primary keys and indexes, and the basic shape of a distributed system: several nodes, network calls, and partial failure. The previous chapters set out why unique IDs are hard and what to ask of an ID scheme. Here we look at the most obvious answer, one shared counter, and find where it stops working.
The idea: one counter, one source of truth
If many machines need unique IDs, the simplest design gives the job to one machine. That machine holds a number. Each request returns the current value and adds one to it.
Uniqueness follows from there being a single place that hands out numbers, as long as increment-and-read is atomic. Two callers can never receive the same value, because the counter serializes them.
Most relational databases ship this feature:
| Database | Feature | Notes |
|---|---|---|
| PostgreSQL | `SEQUENCE`, `GENERATED ... AS IDENTITY`, `serial` | `nextval` is not rolled back with the transaction |
| MySQL (InnoDB) | `AUTO_INCREMENT` | Gaps appear after rollbacks and failed inserts |
| SQLite | `INTEGER PRIMARY KEY`, optional `AUTOINCREMENT` | Single-writer database |
| SQL Server | `IDENTITY` | Gaps possible after restarts or rollbacks |
A working example
The following program uses Python's built-in sqlite3 module. It shows what AUTOINCREMENT guarantees and what it does not.
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute(
"CREATE TABLE orders (id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT)"
)
for item in ["pen", "book", "lamp"]:
cur = conn.execute("INSERT INTO orders (item) VALUES (?)", (item,))
print("inserted", item, "with id", cur.lastrowid)
# Delete the newest row. AUTOINCREMENT never reuses its id.
conn.execute("DELETE FROM orders WHERE id = 3")
cur = conn.execute("INSERT INTO orders (item) VALUES (?)", ("desk",))
print("inserted desk with id", cur.lastrowid) # 4, not 3
print(conn.execute("SELECT id, item FROM orders ORDER BY id").fetchall())
# [(1, 'pen'), (2, 'book'), (4, 'desk')]
conn.close()The IDs are small integers and increase in insertion order. Id 3 is now a permanent gap. Auto-increment promises unique and increasing values. It does not promise that the values are contiguous.
What a central counter does well
Measured against the properties from the previous chapter, a single counter scores well on several:
- Uniqueness is easy to argue for. One writer serializes all requests, so there is no probability to estimate.
- IDs are small. A 64-bit integer takes 8 bytes. A UUID takes 16.
- IDs are ordered. A larger ID was issued later, so sorting by ID sorts by creation order.
- Index inserts are cheap. New keys always land at the right edge of the B-tree, which keeps pages full and hot.
- Nothing extra to operate. The database you already run provides it.
For a single database server, this is usually the right answer. Do not replace it with something more elaborate until you have a concrete reason.
Where it stops working
The counter's strength is also its weakness. Every ID comes from one place, so every ID generation depends on that place.
Throughput
Increments must happen one at a time. The counter value is shared mutable state, so the database takes a lock or latch, writes a log record, and returns. If every ID needs one network round trip of about 1 ms, a single caller can fetch at most about 1,000 IDs per second. Many callers in parallel do better, but they all queue at the same counter. The ceiling is whatever one machine can do for one hot row or one hot sequence.
You can raise that ceiling with faster hardware. You cannot raise it by adding machines, because adding machines adds more callers and not more counters.
Latency
Every write that needs an ID must first reach the counter. If the counter is in another region, each insert pays a cross-region round trip before it can start. A user in Sydney whose counter lives in Virginia waits well over 100 ms for an ID alone.
Availability
If the counter is down, no node can create new records. The rest of your system may be healthy and still unable to accept writes. This is the point where the first chapter's partial-failure warning applies. A single counter turns one machine's failure into everyone's failure.
Failover can reissue IDs
The usual fix for availability is a replica that takes over when the primary dies. The counter now has a new risk. If replication is asynchronous, the replica may be a few increments behind when it is promoted. It then hands out IDs that the old primary already issued.
Suppose the primary issued 5001 to 5010, but the replica had only seen up to 5006. After promotion, the next ID is 5007. Those IDs may already sit in emails, logs, payment-provider records, or caches. Whether you get a clean duplicate-key error or a silent mix-up depends on how much of the old primary's data survived.
Synchronous replication closes the gap, but each ID then waits for a replica acknowledgment, which worsens latency.
MySQL before 8.0 had a related problem on a single server. It kept the auto-increment counter in memory and recomputed it as MAX(id) + 1 after a restart. If the newest rows had been deleted, their IDs could be reused. MySQL 8.0 persists the counter.
Gaps
Sequences in most databases are intentionally non-transactional. If transaction A takes value 10 and rolls back, value 10 is not given back, because transaction B may already have taken 11. Making the counter transactional would force all inserting transactions to wait for each other. So gaps are the price of concurrency. Never write code that assumes IDs are contiguous, for example "the count of orders is the highest ID".
Tuning a single counter
Before giving up on the idea, there are cheaper adjustments:
- Sequence caching. PostgreSQL's
CACHE nlets each session reservenvalues at once. This reduces contention. It also creates gaps when a session ends, and IDs may not appear in global time order across sessions. - Batch inserts. Reserve many IDs in one call, then insert many rows.
- Faster storage and group commit. Reduces the cost of making each increment durable.
These give a constant-factor improvement. They keep the single point of failure.
Multiple counters with offsets
A well-known workaround for availability is to run several counters, each stepping by the number of counters, with different starting offsets. With two counters, one issues odd numbers and the other even. MySQL supports this directly through the auto_increment_increment and auto_increment_offset settings, and it is used in multi-primary replication setups.
class StridedCounter:
"""One of `total` counters. Issues offset, offset+total, offset+2*total, ..."""
def __init__(self, offset, total):
if not 1 <= offset <= total:
raise ValueError("offset must be between 1 and total")
self.next_value = offset
self.total = total
def next_id(self):
value = self.next_value
self.next_value += self.total
return value
a = StridedCounter(offset=1, total=3)
b = StridedCounter(offset=2, total=3)
c = StridedCounter(offset=3, total=3)
print([a.next_id() for _ in range(4)]) # [1, 4, 7, 10]
print([b.next_id() for _ in range(4)]) # [2, 5, 8, 11]
print([c.next_id() for _ in range(4)]) # [3, 6, 9, 12]The three streams never overlap, so the counters need no coordination to stay unique. If one counter fails, the others keep issuing IDs.
The cost is real, though:
- Global order is lost. If counter
bis busier thana, ID 11 may be created before ID 7. Sorting by ID no longer sorts by creation time. - The cluster size is baked into every ID. Going from 3 counters to 4 changes the stride. You must move every counter's next value past all IDs already issued, and the old and new streams must not collide. This is tricky to do online.
- Gaps grow. An idle counter leaves long holes in its stream.
This approach keeps uniqueness and trades away ordering. The next chapter looks at a different way to cut coordination while keeping one logical source: handing out blocks of IDs.
Operational and security notes
Sequential IDs expose information. A competitor who creates an account on Monday and another on Friday can subtract the two IDs and estimate your signup rate. Sequential IDs in URLs also make enumeration attacks easy, where an attacker tries /orders/1001, /orders/1002, and so on. This does not replace access control, but it makes missing access control far easier to exploit. A later chapter covers this in detail.
When to use a central counter
Use one when:
- You run a single primary database, and writes fit within one server.
- You want small, ordered keys and cheap index inserts.
- Exposing sequence information is acceptable, or you map to public IDs separately.
Look at other schemes when:
- Writers in several regions must create records without cross-region calls.
- A counter outage must not stop writes.
- You need to generate IDs offline, such as in a mobile client, before the database sees the record.
- IDs are public and must not reveal volume or be guessable.
Exercise
A team runs two MySQL primaries in different regions with autoincrementincrement=2, one with offset 1 and one with offset 2. They sort their audit log by id to see events in order. Why can this give the wrong order, and why does adding a third primary later require care?
Show answer
Each primary issues IDs independently, so a busier primary's IDs climb faster. An event on the quiet primary can get a lower ID than an earlier event on the busy one, so sorting by ID does not match creation time. Adding a third primary changes the stride from 2 to 3. The new stride and offsets must be chosen so the new streams never produce a value already issued by the old ones, which usually means moving every counter past the current maximum before the change.
Exercise
A primary issued IDs up to 5010, then failed. The asynchronous replica had applied only up to 5006 and was promoted. What problem can happen, and which replication setting would prevent it, at what cost?
Show answer
The new primary will issue 5007 to 5010 again, so IDs already seen by clients or external systems are reused. Synchronous replication prevents this, because the primary does not acknowledge an ID until a replica has recorded it. The cost is higher latency for every ID or write, and reduced availability if the replica is unreachable.