Internals¶
fdyno is a stateless Go interpreter for DynamoDB requests. FoundationDB holds every durable byte and supplies transactions, ordering, replication and recovery.
flowchart LR
accTitle: Signed SDK requests pass through fdyno into FoundationDB
SDK["AWS SDK"] --> API["fdyno"] --> FDB["FoundationDB"]
class API service
Process state¶
All state needed after a restart is in FoundationDB.
| In FoundationDB | In the process, replaceable |
|---|---|
| Table schema, tags, policies, TTL settings | Connections and in-flight requests |
| Items, chunks, index entries | Metrics |
| Stream records | Caches of table metadata, checked against FoundationDB before use |
| Backups and restore jobs | Credentials and settings from the environment |
| Transaction tokens | Alternator test-compatibility settings |
| Worker leases and cursors |
Each transaction checks a cached schema at its read version before it uses it, so losing a cache loses no data.
What makes a metadata cache hit safe¶
FoundationDB keeps one cluster-wide metadata version
(\xff/metadataVersion). A transaction reads it with its read version, at
no storage cost. Every change of table metadata, and every delete or move
of a table directory, bumps it in the same transaction.
| At the read version | Result |
|---|---|
| Metadata version equals the one the entry was last checked at | Use the cached schema. |
| Metadata version changed, table revision matches the entry | Use the cached schema, and record the new version. |
| Metadata version changed, table revision differs | Reload the metadata. |
The directory prefix identifies the keyspace, not just the table name. A cache entry carries that prefix, the digest of the metadata (the revision) and the metadata version it was last checked at. Speculative reads based on the cached schema must discard their result if the check fails.
A mutating transaction still carries a read conflict on the table's
revision key, also when the metadata version alone shows the entry
current. If DDL wins the race, the write retries against the new metadata
rather than committing with the old index or stream layout.
table_metadata_cache in the JSON metrics counts the checks: hits
(unchanged metadata version), misses (revision read) and stale.
See the metadata cache tests
and directory reuse tests.
Request path¶
- The request gets one deadline for its whole life (30 s by default).
- fdyno bounds the headers and body, verifies the signature and picks the action.
- The operation validates the request, evaluates expressions and runs a read-only or read-write transaction.
- A read-only transaction returns after its reads complete; it never commits.
- Writes succeed after commit. Atomicity is per transaction.
- Errors use DynamoDB codes. Split batches keep earlier
commits on unknown-outcome errors or
200withUnprocessedItems.
The data listener runs fdyno's own HTTP/1.1 loop (internal/httpd). It
writes the same bytes as Go's net/http server for the requests fdyno
serves. Common reads and writes use pooled transactions in
internal/fdbget, about one C call per read or commit.
How a request is read¶
One parser reads every request head
(parseHead).
There is no second parser and no net/http fallback.
- A scanner checks each line of the head as it arrives: the request line,
the header names and the value bytes. A bad line gets
net/http's reply. parseHeadbuilds the request. For every head thatnet/httpaccepts, it gives the same request: method, target, version, headers,Host, connection close,Content-LengthandTransfer-Encoding.- Every other head gets
net/http's status:400for a bad request line, header name,HostorContent-Length;501for an unsupportedTransfer-Encoding;431for headers over 68 KiB. See request limits.
The usual SDK head (POST / HTTP/1.1) skips URL parsing. It takes about
0.9 µs and one allocation on one CPU; http.ReadRequest takes about 3.3 µs
and 28 allocations. Each connection reuses one request, header map and
value slice. Two fuzz tests check the match with net/http:
FuzzRequestHead compares the parsed request, and
FuzzServerMatchesNetHTTP compares what the handler sees and the reply
bytes.
Client half-close. A client can shut down its sending side while its
requests run, for example after it pipelines several requests. fdyno then
cancels the requests in flight and answers 499 (client_closed, see
monitoring). The requests after them in the pipeline start
cancelled and also get 499. Go's net/http server does the same when the
handler reads its body first, and fdyno's handler always does. fdyno keeps
this behavior on purpose. A write that gets 499 may have committed: treat
it as an unknown outcome.
Fast paths¶
A fast path keeps the regular path's results, errors and conflict checks, on a pooled FoundationDB C-API transaction. It does not promise the same physical reads or order: it can issue reads together, and it can reuse a table revision it already read. Most fast paths share the operation code that decides the result. Call counts below are the estimates in each file's header comment.
GetItem, BatchGetItem, Query and Scan write every returned item from
its stored bytes with one encoder
(stored_item_json.go).
It writes every item the store can hold, byte for byte as the generic item
encoder would. TTL expiry, key conditions, sizes and cursors are read from the
stored bytes. A FilterExpression, a legacy filter or a nested projection
decodes the item to evaluate it; the response still comes from the encoder.
| Step | Check | Outcome |
|---|---|---|
| 1 | Run one pooled transaction at a fresh read version | Decided: return the result or the error, for example a failed condition. |
| 2 | The attempt failed (a retryable FoundationDB error, a stale cached table, no free pooled transaction) | Run the same attempt again on fdbget, with the regular retry loop's error rules. |
| Path | Serves | FoundationDB calls |
|---|---|---|
getitem_ |
Every GetItem attempt; a retry runs the same attempt again on fdbget |
About one C call per read instead of about thirteen. |
batch_ (Batch, the SELECTs of a Batch), txn_ (Transact, a read-only Execute: transact): every attempt; a retry runs it again on fdbget |
Up to 100 keys | One call issues every item read and the read version, one wake-up when all are ready, one call copies every value; instead of about five calls per item. |
query_, item_ |
Every Query and Scan page attempt (base table and indexes); a retry runs the same attempt again on fdbget |
One fdbget transaction per page: its first read gets the read version, and the range reads, the index sample and LSI hydration use the same transaction. The table revision is checked at that version. |
streams_ |
Every Get and Get attempt; a retry runs it again on fdbget |
With cached table metadata, the shard's trim-head read and its range read go with the transaction's first call; the revision is checked at that version. Otherwise the stream (a retired generation, a deleted table's kept stream) is resolved first in the same transaction. Records are written from the stored bytes. |
write.go |
Every attempt of PutItem, Update and Delete (run, the one body) |
About three Go-to-C crossings instead of about twenty binding calls. For a whole-item write that reads its item, one crossing gets the read version and reads the old item and the table revision together, and one crossing commits. A blind write that runs alone reads the revision with its read version. A blind write that runs while other fdbget writes are in flight starts with the read version only; it reads the metadata version in one more crossing, and the revision only if some table metadata changed. When a recent read version is known current for the table, the attempt starts at it instead: a blind write then begins and commits in one crossing, and a write that reads its item reads only the item (read modes). |
txn_ |
Every attempt of a Transact (its only path) |
A few calls instead of about ten per item: every item read and the token record read in one call and one commit. An attempt that runs alone adds each table's revision to that call; concurrent attempts check the metadata version. |
No fast path declines a request: each reads uncached metadata first and retries a stale revision or a busy pool on fdbget.
A fast read answers some errors itself, as the regular path would. These are
an ended context, FoundationDB's transaction timeout, and a FoundationDB
throttle (1213 or 1051, returned as ProvisionedThroughputExceededException).
DYNODB_SLOW_REQUEST_MS times the fast paths; it does not turn them off.
GetItem, BatchGetItem, TransactGetItems, Query, Scan, GetRecords,
GetShardIterator, PutItem, UpdateItem, DeleteItem and TransactWriteItems have
no regular path: a failed attempt
runs again on fdbget at a new read version, with FoundationDB's backoff after a retryable
error. An fdbget write that decides
an operation error, such as a failed condition, returns it directly.
The retry loop of a write sorts failures as the regular retry loop does. It retries an unknown commit only for a tokened transaction, which checks its token first. Any other write ends with an unknown outcome (fdyno's own retries). Worker writes under a lease fence use the regular path. Read-only fast paths use snapshot reads; the regular read transaction never commits, so neither adds a conflict check. See which reads are conflict-checked. The deterministic simulation runs each seed's sequential workload through both paths and compares the complete API traces, not the client-call counts. It uses simulated FoundationDB, not the native C client, and its concurrent scenes do not compare the two paths.
Foreground requests use one or more transactions. Background workers use bounded transactions and per-worker leases; TTL ranges have separate leases.
How FoundationDB features are used¶
| FoundationDB feature | fdyno uses it for |
|---|---|
| Directory layer | One keyspace per table and per service-owned area. |
| Tuple layer | Ordered keys for partitions, sort keys, index entries and page cursors. |
| Transactions | Condition, item, index entries and stream record in one commit. |
| Conflict detection | Isolation for conditions, read-modify-write updates and queries. |
| Versionstamped keys | Stream positions assigned at commit, in commit order. |
| Range reads | Query, Scan and bounded pages without loading a table into memory. |
| Watches | Waking Get calls when a record arrives. |
| Batch priority | Background work that yields to foreground requests. |
fdyno has one storage backend. Replacing FoundationDB would mean rebuilding ordering, conflict detection and versionstamps. The key inventory below is the format reference.
A retryable error reruns the transaction body, so operation code keeps per-attempt state local, with no side effects outside the transaction. Guarantees lists what each failure does to data.
Primary keys and ordering¶
attrToTupleElement maps key attributes to tuple elements:
| DynamoDB key type | Tuple element | Ordering |
|---|---|---|
S |
Tuple string | UTF-8 byte order |
B |
Tuple byte string | Byte order |
N |
Order-preserving byte string | Normalized, split into sign, exponent and digits, so byte order is numeric order (the number's text would put "100" before "2") |
An item key is ("i", hashValue [, sortValue]). So a partition is the prefix
range a Query reads. ExclusiveStartKey is the packed tuple that starts
the next page.
Key explorer: the item key ("i", "acct-7", sortableNumber(100.5)) and the index key ("x", "ByStatus", "OPEN", sortableNumber(1710000000), "acct-7", sortableNumber(100.5)), byte by byte.
Durable key inventory¶
Paths are conceptual tuples; the directory layer assigns physical prefixes.
The metadata revision mr is a raw 32-byte SHA-256 of exact JSON m,
written/deleted atomically with it. Full reads verify the pair; watches,
cached reads and mutation prefetch validate it at their read version.
It is an integrity/cache revision, not a format version.
| Key | Value format | Bounds and integrity | Lifetime |
|---|---|---|---|
dynodb/ |
JSON snapshot |
One FoundationDB value; JSON and table state are validated | Table lifetime |
i/... |
One deterministic encode value |
At most 48,000 encoded bytes; strict item decode | Item lifetime |
x/... |
One deterministic encode projection |
At most 48,000 encoded bytes; strict item decode | Index-entry lifetime |
vgt/ |
Packed lower-bound key for untrimmed records | Earlier positions or pruned epochs return Trimmed; a removed generation returns Resource |
Written with trim deletion; cleared with the epoch or generation |
vg/ |
FDYNOC01, optionally keys-by-name and old-image-delta flagged |
One FoundationDB value; strict record and item decode | Until retention or whole-generation removal |
vgb/ |
Tuple containing one complete versionstamp, written by Set |
Exact epoch start, preceding epoch end, or final disable boundary; reader checks the tuple and stamp | Cleared with the epoch or generation |
<table>/ |
PITR undo record: FDYNOC01 with keys and old image only |
One FoundationDB value; strict record and item decode | Written in the item's transaction while PITR is on; trimmed by whole commit version after the recovery period plus the CDC skew margin; cleared by disable |
<table>/ |
Tuple (last trimmed versionstamp, |
Preflight and late trim checks can fail with Invalid; the async worker fails early with Point if the trim floor passes the requested time |
Written with each trim; cleared by disable |
dynodb_ |
JSON storage format 3 with generation and publication state; format 4 (Items = retained-table) for a deleted PITR table's SYSTEM backup |
Only COMPLETED metadata reads as a backup; binaries without format 4 fail to decode it |
Until Delete; stale staging work is collected; a SYSTEM backup cannot be deleted and expires 35 days after Delete |
dynodb_ |
The directory of a deleted PITR table, moved unchanged; its m and mr keys are cleared |
Read by the restore of its SYSTEM backup, and by its kept stream | Removed with the SYSTEM backup |
dynodb_ |
The directory of a deleted table whose stream is kept, moved with its key prefix; only the stream subspaces (vg*) are left |
Read through the kept stream record | Removed with the record |
dynodb_ and ("m", |
JSON record v1 (table_id, deleted_, expires_, path, owned) and the table metadata at the delete, stream disabled |
Read when a stream ARN's table is gone or re-created; unknown versions skipped; a missing directory reads as not found | Dropped by pitr-trim after expires_ (24 hours after the delete, or the end of a disabled generation's retention) plus DYNODB_ |
dynodb_ |
FDYNOB01, item count, then length-prefixed encode values |
One value of at most 100,000 bytes; tuple manifest validates count, size, SHA-256, frames, and trailing bytes | Immutable backup generation |
dynodb_ |
JSON restore job, version 2, for a backup or a PITR restore | Identity, state, counters, lease and fence validated; an unreadable or version 1 record ends the job FAILED and removes its CREATING target |
Completed/failed metadata stays 24 h from Updated as the admission record. |
dynodb_ |
JSON backup, v1: backup ARN, source identity, generation and page count (or retired directory), and the cursor (page, or last item key |
Fenced; written with every applied page | Stays with the 24 h admission record. |
dynodb_ |
Empty: the restore pin | Delete (USER backups) and the SYSTEM expiry read it in their removal transaction; a pin of a running job blocks removal (Backup), a pin of an ended job is cleared |
Cleared when the job completes, fails or is cancelled. |
dynodb_ |
JSON pitr, v1: source, epoch, phase and exclusive cursor |
Fenced phase and progress state | v2 terminal state stays with the 24 h admission record. |
dynodb_ |
One encode value per item: the key-ordered PITR staging state |
Strict decode; fenced cursor/data progress | Cleared on completion, fenced failure or user cancellation. |
Export job pd/ and pi/ |
One old-image value or an explicit absent marker | Strict decode; the staged image is not overwritten | Cleared with the job's staging state |
dynodb_ |
Tuple ("v2-sha256", |
Exact tuple fields and 32-byte digest | Ten-minute request-token window, then GC eligible |
dynodb_ |
Packed key of the next token row to scan | A byte-string tuple element, so it cannot collide with a token (a string element) | Written with each token-GC page; cleared when the walk wraps |
dynodb_ |
Tuple (owner, |
Tuple type checks | Renewed while a worker owns the lease. TTL drain range leases, ttl-sweeper/, are released after each pass |
dynodb_ |
Tuple (owner, |
Worker effects check the epoch with a conflict read; the expiry row is a snapshot owner check | New on acquisition after expiry or release, including by the same owner; renewal preserves it or creates it for a legacy lease; cleared on release |
dynodb_ |
JSON {v, |
Version 1 only, and the TableId and creation time of the table; anything else reads as no record |
Advisory Describe statistics, rewritten when older than six hours, cleared after the table is deleted; older binaries never read it |
dynodb_ |
JSON {version,: up to 15 ascending item-key suffixes |
Version 1 only, ascending non-empty bounds; anything else reads as one range | Advisory. Rewritten when older than 10 minutes; cleared when the table leaves the TTL registry. Older binaries never read it |
dynodb_ |
Tuple (3, |
Record format 3, cluster version 12 only; the store format check refuses any other value | Written once by the first start on an empty FoundationDB; a store with data and no record is refused; never rewritten |
dynodb_ |
JSON registration written by builds before the store format check | Never read | Left in place; harmless |
<table>/ |
Empty value; bucket is floor(expiry)/ of the item's numeric TTL attribute |
Key decodes to the item key; the item's own TTL attribute decides deletion | Moved or cleared in the same transaction as every TTL-enabled item write; stale entries are cleared by the drain |
<table>/ |
JSON {complete, |
A corrupt value restarts the backfill wrap | Table lifetime; cleared when TTL is re-enabled |
dynodb_, ("streams", and ("pitr", |
Empty for TTL and PITR tables; Latest for tables whose stream was ever enabled |
An index, not authority: readers check each listed table's metadata; workers prune entries whose table is gone or flag is off | Set or cleared with every table metadata write; cleared by Delete |
dynodb_, k = 0…63 |
Packed tuple of the sorted names of the tables (including CREATING ones) whose FNV-1a hash mod 64 is k |
Read only after ("built"); until then /readyz is not ready and table listings answer a retryable 400 Throttling |
Rewritten, never cleared, in the transaction that creates, removes or moves a table directory; a write that would pass 90,000 bytes fails with Limit |
dynodb_ and ("cursor") |
v1 once every table name is in the set; the build's next key in the dynodb directory's child list |
The build runs at service start (Run): 100 names per step from the cursor; a read that runs out of time halves its range, and a range that cannot be halved is read without that limit |
built is set by the first Create on an empty store, or at the end of the build; permanent |
dynodb_ and ("changes") |
The tables with a GSI in any status, each as <table name>\x00<Table, in the 64-bucket layout of dynodb_ but bucketed by table name; changes is a versionstamp rewritten with every bucket change |
The GSI apply worker reads changes every 1 s and the buckets only when it moved, and opens only the tables that are new or have a new TableId |
Rewritten with every table metadata write and delete (a re-create swaps the TableId in one transaction) |
dynodb_, ("built"), ("cursor") |
The GSI backfill job keys (Table, packed, in the same 64-bucket layout as dynodb_ |
The backfill pass lists its jobs from the buckets once ("built") is set; before that, the pass first builds the set from the job keys (the same build as the table names) |
Rewritten in the transaction that writes or clears a job key (put, retire); built is set by the first job on a store without a job directory, or at the end of the build |
A two-image change record fits one 100,000-byte value even without savings from the compact forms. Each image is at most 48,000 encoded bytes. The primary-key item needs at most 3,600 bytes:
- four bytes for its codec header and count;
- up to two names of 255 bytes;
- 2,048 bytes for the partition value and 1,024 for the sort value;
- seven framing bytes per entry.
Allow 34 bytes
for the CDC header and frames, including the optional logical-size field.
Even reserving another 33 bytes for the TTL identity (TTL never has two
images), the bound is 2 × 48,000 + 3,600 + 34 + 33 = 99,667 bytes.
Unknown markers, malformed manifests, missing chunks, digest mismatches, and trailing bytes fail closed.
Storage invariants¶
- A committed base-item mutation, its LSI changes and its GSI change records share one transaction. A worker applies the GSI change records later.
- A stream record, when emitted, shares that transaction.
- A manifest and its complete value become visible atomically.
- Every index entry ends with the complete base key, so duplicate index values do not collide.
- Active index entries contain only their declared projection.
- Metadata under
mis the durable source for schema, streams, tags, policies, TTL configuration, status, and restore identity. - Backup and restore batches contain logical items. Restore derives current base and index keys instead of copying physical keys.
These invariants back the guarantees in Writes and Consistency.
The worker lease also separates expiry for election from epoch for authorization. A renewal changes the expiry without conflicting with the holder's effect transaction. A takeover changes the epoch, so a paused worker's checked transaction cannot commit over the takeover. The effect check does not compare expiry with wall time. This fence requires every worker binary to understand epochs. See the renewal and takeover tests.
Encoding details¶
Item value bytes¶
The value at ("i", "order#1") in
what one write commits is the whole item
in codec version 2. For {"pk": "order#1", "status": "paid"} it is 37 bytes:
| Bytes | Meaning |
|---|---|
00 00 02 |
Header: two zero bytes, then codec version 2 |
02 |
Attribute count 2, as a LEB128 varint |
00 02 70 6b |
Name length 2 (big-endian uint16), "pk" |
01 00 00 00 07 |
Tag 01 (S), length 7 (big-endian uint32) |
6f 72 64 65 72 23 31 |
"order#1" |
00 06 73 74 61 74 75 73 |
Name length 6, "status" |
01 00 00 00 04 70 61 69 64 |
Tag 01 (S), length 4, "paid" |
| Tag | Type | Payload |
|---|---|---|
01 |
S |
uint32 length, UTF-8 bytes |
02 |
N |
uint8 length, the number's text (at most 255 bytes) |
03 |
B |
uint32 length, raw bytes |
04 |
BOOL |
one byte: 00 false, 01 true |
05 |
NULL |
none |
06 |
SS |
count, then per member: uint32 length, UTF-8 bytes |
07 |
NS |
count, then per member: uint8 length, text |
08 |
BS |
count, then per member: uint32 length, raw bytes |
09 |
L |
count, then one tagged value per element |
0a |
M |
count, then per entry: uint16 name length, name, tagged value |
- Sorted names. Attribute names and map keys are written in sorted order, and the decoder rejects names or map keys that are not strictly sorted. The codec does not sort list elements or set members; it writes them in the order it receives them.
- A number value is its normalized text. Every write normalizes numbers
before it encodes them: no leading zeros, no trailing decimal zeros, and
the exponent expanded. So
100.5,100.50and1.005E2all store02 05 31 30 30 2e 35. A value needs no sort order, unlike the number key encoding. - Counts. Every count is a minimal unsigned LEB128 varint of 1 to 5
bytes, at most 2^32 − 1: 127 is
7f, 128 is80 01, and 130,000 isd0 f7 07. The decoder rejects a varint that is not minimal or exceeds 32 bits, so every accepted count has one byte form. - Nesting. The codec refuses nesting deeper than 32 levels.
- Bound. The codec refuses an encoded item over 8 MiB, a safety bound far above the 48,000-byte item limit.
One version. fdyno reads and writes only version 2. The empty item is
00 00 02 00. A value that does not start with 00 00 fails with
unsupported item encoding: no codec version 2 header. An unknown version,
such as 00 00 03, fails with unsupported item codec version 3. A decode
error fails the request; it never returns a partial item.
Base rows. The encoded item is one value at its item key. A write sets that key. A delete clears it.
Sources: codec.go
and fdb_store.go.
Physical encoding keeps the exact tuple map, codec bytes, index projections, backfill algorithm and worked key example. Its diagrams are implementation detail, not extra public storage interfaces.
Not guaranteed¶
Raw keys are internal, not an interface. There is no local item store, cache of record or write-ahead log. Backups contain logical items; restore encodes them in the current store format.
- No second replication layer. FoundationDB already replicates; a second layer would add a second failure model.
- No eventually consistent replica. Table and LSI reads use FoundationDB transactions, so they are current by default. Only a GSI, applied from its change log, is eventually consistent, as in DynamoDB.
- No unbounded transactions. Large work is paged.
- No cross-region replication at the fdyno layer.
The cost: index and stream work sits on the write path, and the service needs FoundationDB to serve anything.
ARCHITECTURE.md in the repository is the contributor guide: code layout, packages and design notes.
How we know: protocol models and runtime checks.