/foundationdb-dotnet-skills:foundationdb-advanced-layersfrom foundationdb-dotnet-skills
Advanced engineering for FoundationDB layers using the .NET client. Covers cluster internals, transaction lifecycle, latency/throughput optimization, high-contention avoidance, and distributed patterns like change feeds and version-stamp logs.
Ships in foundationdb-dotnet-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
This is the advanced tier. The foundationdb-keys-and-layers skill (key encoding, subspaces, the IFdbLayer<TState> pattern) and foundationdb-transactions skill (retry loop, idempotency, atomics, watches) are prerequisites — this skill assumes them and explains the why underneath, plus the patterns for performant, distributed, multi-node layers.
A fully worked, compile-checked reference for everything in §5–§6 lives in samples/SkillValidation/BookStore.cs + BookStore.ChangeFeed.cs.
(FoundationDB's published architecture; the constraints below fall out of it directly.)
| Role | Responsibility |
|---|---|
| Coordinators | Small Paxos group; elect the cluster controller, hold the cluster file. Clients bootstrap here. |
| Cluster Controller | Singleton; recruits/monitors all other roles, drives recovery. |
| Master / Sequencer | Hands out monotonically increasing versions — read versions and commit versions. The global logical clock. |
| GRV proxies | Serve get-read-version: ask the master for the latest committed version, confirm the tlogs are still live (so a read version is never stale after a recovery); throttled by Ratekeeper. |
| Commit proxies | Drive commits: get a commit version from the master, send conflict ranges to resolvers, make mutations durable on the tlogs. |
| Resolvers | Hold the last ~5 s of committed writes in memory; compare a committing tx's read-conflict ranges against them → this is where conflicts (not_committed, 1020) are decided. |
| Transaction Logs (tlogs) | Durable, replicated WAL; receive mutations in version order and only ack once fsync'd on a quorum. |
| Storage servers | Hold the sharded, replicated data; keep ~5 s of mutations in memory + on-disk data "as of 5 s ago"; serve reads via MVCC. |
| Ratekeeper / Data Distributor | Singletons: throttle transaction start rate near saturation / keep shards balanced across storage servers. |
Lifecycle of a read-write transaction:
Why the rules you already follow exist:
transaction_too_old (1007). It's also why a recovery "fast-forwards 90 s" and aborts in-flight transactions. → keep transactions short; page long scans across many transactions.The native client pipelines concurrent requests. The enemy of latency is a serial data dependency — code that reads, inspects the result, then reads again. Each such hop is a full client↔cluster round-trip that cannot be hidden.
Batch independent reads — never await them in a loop:
// ❌ N round-trips (each await blocks on the previous)
foreach (var id in ids) results.Add(await tr.GetAsync(subspace.Key(id)));
// ✅ one batched multi-read
Slice[] values = await tr.GetValuesAsync(ids.Select(id => subspace.Key(id))); // GetValuesAsync<TKey>(...)
// ✅ or issue concurrently and let them pipeline into ~one round-trip
Slice[] vs = await Task.WhenAll(tr.GetAsync(k1), tr.GetAsync(k2), tr.GetAsync(k3));
tr.GetValuesAsync(keys) reads many independent keys in one logical batch (this is what a document store's metadata fetch uses). For ranges, GetRangeAsync(range, options) returns a page per round-trip — tune FdbRangeOptions (WantAll, WithLimit, streaming mode) to your access pattern.
Collapse read→decide→read dependencies. If you find yourself reading key A only to decide whether/how to read B, ask whether the information can be encoded so a single read carries it. (The change-feed in §5 does exactly this: instead of "read the trim marker, then range-read the feed," the trim signal is a tombstone inside the feed, so one GetRange returns both the data and the eviction signal — see §5.4.) If you genuinely can't, issue both in parallel with Task.WhenAll and discard the wasted one in the rare case.
Other levers:
tr.Snapshot.GetAsync/GetRange) skip read-conflict tracking — cheaper and conflict-free; use when a slightly stale read is acceptable.Fdb.Bulk.* (it manages batching and the 5-second window for you).Conflicts are resolver verdicts on read-conflict ranges. A key that many transactions read-then-write serializes there. Avoid it:
AtomicAdd64, AtomicIncrement32/64, AtomicMax/Min, AtomicOr/And/Xor) — they don't read, so they create no read-conflict and never conflict with each other. Counters, statistics, signal keys.AddConflictRange) only when your reads/writes don't already imply the semantics you need.The sequencer is the only source of "now" that every node agrees on. Use it; never use node-local wall clocks for cross-node decisions.
tr.GetReadVersionAsync() → the read version: a monotonic, cluster-wide logical clock, identical regardless of which node reads it. Use it for leases / liveness, ordering, "as-of" reasoning.tr.CreateVersionStamp() + SetVersionStampedKey/Value → the commit version, assigned atomically at commit. Globally ordered, collision-free → the backbone of queues, logs, and change feeds (§5).GetVersionStampAsync() / GetCommittedVersion() → recover the version a transaction committed at.⚠️ Two clock traps (both real, both bite):
- Local wall clocks have no shared "now." Comparing a timestamp minted on node A against node B's
DateTime.UtcNowis meaningless (skew, drift, NTP steps, VM pauses) — like comparing times across relativistic frames. Cross-node liveness must use the database clock.- The version tick-rate is not constant (~1e6/s but it drifts; idle clusters advance slower). So do not convert a version delta into a duration (
now - lease > N_versionsis unsound). Instead, store a DB-sourced token and test it for change (equality), and measure elapsed time only as the gap between an observer's own consecutive local reads (§5.3).
A shared clock removes skew, but not the fundamental failure-detector impossibility: you still cannot distinguish "slow" from "dead." So liveness is always a policy (a threshold) backed by evict-and-resync, never a proof.
A change feed lets other nodes observe a stream of changes and maintain an in-memory view. It composes every primitive above. Full compile-checked code: BookStore.ChangeFeed.cs.
Each mutation appends a change under a commit-ordered VersionStamp and bumps a single watched signal key — all in the same transaction as the data write, so the feed can never disagree with the data:
var stamp = tr.CreateUniqueVersionStamp(); // distinct per change, even several per tx
tr.SetVersionStampedKey(subspace.Key(SUBSPACE_FEED, stamp), FdbValue.ToJson(change));
tr.AtomicIncrement64(subspace.Key(SUBSPACE_SIGNAL)); // wake every subscriber; conflict-free
The consumer reads pages after its cursor; when caught up, it watches the signal key (outer token, not tr.Cancellation), awaits outside the transaction, then re-reads. Expose it as IAsyncEnumerable<T> and wrap thinly as a Channel<T> or a callback. The VersionStamp of the last entry is the resume cursor.
A version-stamped log grows forever, so a GC must trim it. Trim everything consumed by all live subscribers (up to the slowest live cursor); if nobody's live, drop the backlog. "Live" is decided without comparing clocks:
unchanged for N polls ≈ N × the observer's own local delay) — equality-check only, never version→time, never cross-node timestamp comparison;A subscriber frozen long enough gets evicted and the GC reclaims past its cursor → it missed changes and its view is untrustworthy. It must be told. The efficient signal is a tombstone: when the GC reclaims (·, horizon], it leaves one empty-value entry at the horizon's versionstamp.
GetRange — an empty value deserializes to null (a real change is always non-null JSON), so it's detected with no extra read / no serial dependency.ChangeFeedOutOfSyncException that propagates through the enumerable / channel / callback; the consumer catches it, reloads current state, and re-subscribes from "now."This is the same contract as Kafka's OffsetOutOfRange / DynamoDB Streams' TrimmedDataAccessException: you can't prevent a too-slow consumer from missing data — you detect it cleanly and force a resync.
GetValuesAsync), parallel (Task.WhenAll), or encoded into one read (tombstone-style)?await-ed in a loop?Fdb.Bulk.*?State confined to the transaction?What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub snowbanksdk/foundationdb-dotnet-client --plugin foundationdb-dotnet-skills9 skills in this plugin
/crystaljsonHow to use CrystalJson, the custom JSON library in SnowBank.Core (namespace SnowBank.Data.Json). Covers the JsonValue DOM (JsonObject / JsonArray / JsonString / JsonNumber / JsonBoolean / JsonNull / JsonDateTime), the read-only vs mutable model, the CrystalJson static API (Serialize / Parse / Deserialize) and CrystalJsonSettings, the Roslyn source generator for fast reflection-free serializers and read-only/writable proxies ([CrystalJsonConverter] / [CrystalSerializable]), the IJsonSerializable / IJsonPackable / IJsonDeserializable interfaces, MutableJsonValue / ObservableJsonValue and JsonPath. Use whenever code parses, builds, reads, mutates, or serializes JSON with these types, reads optional fields with defaults, declares a generated JSON converter/proxy, or implements custom JSON (de)serialization. Use it even when the request only says "serializer", "converter", or "serialize/deserialize a record, document, or model" without naming JSON: in SnowBank-based code (document stores, sync layers, Layers, models) document and message (de)serialization goes through CrystalJson, not System.Text.Json or Newtonsoft./foundationdb-aspireHow to run a FoundationDB cluster and connect to it from .NET — getting the IFdbDatabaseProvider that the keys/transactions/layers skills assume you already have. Covers the ways to get a provider (plain DI services.AddFoundationDb, FdbDatabaseProvider.Create, or Aspire), the Aspire AppHost integration (FoundationDB.Aspire.Hosting — builder.AddFoundationDb starts a Docker cluster, AddFoundationDbCluster connects to an existing one), the Aspire client integration (FoundationDB.Aspire — builder.AddFoundationDb reads the injected connection), wiring with WithReference and WaitFor, launching with the aspire CLI vs plain dotnet run plus launchSettings, the native client (libfdb_c via UseNativeClient, the platforms FoundationDB.Client.Native ships, and the macOS system-library fallback), and the client-vs-cluster version-compatibility rule (FoundationDB.Client.Native follows the cluster's major.minor, FoundationDB.Client is independent of it, apiVersion stays within what both the binding and the native client support). Use whenever code opens or connects to a cluster, registers AddFoundationDb, runs an Aspire host, or hits libfdb_c load failures or transactions that hang on a fresh cluster./foundationdb-keys-and-layersHow to correctly encode keys and values, use subspaces and the Directory layer, and write custom "Layers" with the FoundationDB .NET client (FoundationDB.Client / SnowBank). Covers the lazy strongly-typed key structs (subspace.Key(...), FdbTupleKey, FdbRawKey, FdbKey.Increment / Successor / Dump), the tuple encoding (TuPack, IVarTuple, STuple), value encodings (FdbValue.ToBytes / ToTextUtf8 / FromTuple / ToJson / ToFixed64LittleEndian and which one a given access pattern requires), subspaces and ISubspaceLocation, the Directory layer (FdbDirectoryLayer, FdbPath, FdbDirectorySubspace), and the IFdbLayer contract with its per-transaction Resolve(tr) State that must never escape the transaction. Use whenever code reads or writes FoundationDB keys, builds or decodes a tuple key, picks a value encoding, resolves a subspace or location, designs a key layout for a table / secondary index / queue / document collection, reasons about key ordering, prefixes and range boundaries, or defines a class that stores data in FoundationDB. Also use it for "how do I model X in FoundationDB", for range scans that return too much or nothing, and for keys that are too big. Read this BEFORE writing or reviewing any such code./foundationdb-transactionsHow to correctly run transactions with the FoundationDB .NET client (FoundationDB.Client / SnowBank): the db.ReadAsync / WriteAsync / ReadWriteAsync retry loop and why a handler must be safe to run more than once, the 5-second and size limits, conflicts and how to avoid them, snapshot reads, explicit conflict ranges, atomic mutations (AtomicAdd32/64, AtomicIncrement, AtomicMin/Max and the lexicographic ByteMin/ByteMax, AtomicAnd/Or/Xor, AtomicCompareAndClear, AtomicAppendIfFits), and watches. Use whenever code opens a transaction or calls BeginTransaction, writes a read-modify-write, increments a counter, waits on a key with a watch, pages a large range scan across transactions, or hits an FdbException: NotCommitted, TransactionTooOld ("Transaction is too old to perform reads"), CommitUnknownResult, TransactionTimedOut, transaction_too_large. Also use it for "why does my transaction keep retrying / conflict / run twice", for high-contention or write-hot keys, and before deciding that a value must be read and written back. Pairs with the foundationdb-keys-and-layers skill./snowbank-betterhttpHow to make outbound HTTP calls with BetterHttpClient (SnowBank.Networking.Http) in an ASP.NET Core or generic-host .NET application - the DI story and the request API. Covers the one-policy-plane model where a client NAME maps to one effective policy that lives in the pooled handler chain, so every client gets the same behavior: a typed client, a keyed client, IHttpClientFactory.CreateClient(name), and the bare IHttpMessageHandlerFactory.CreateHandler(name). Covers AddBetterHttpClientDefaults (routes every factory client through the map), AddBetterHttpClient(name, ...) returning an IBetterHttpClientBuilder for standard chaining (AddHttpMessageHandler, AddAsKeyed, typed clients), the AddBetterHttpClientConfiguration override layer bound from an appsettings section, the mandatory INetworkMap transport seam (NetworkMap in production, the virtual network inside distributed tests, with packet capture on every chain automatically), BetterHttpClientOptions (default headers and UserAgent, cookies, credentials, TLS server-certificate callbacks and the self-signed/trusted-roots helpers, hooks, delegating handlers), the universal SendAsync(request, ctx => ...) lifecycle with BetterHttpClientContext that now runs the request stage on any client, the Create*Request builders, typed protocols (RestHttpProtocol, BetterHttpProtocolFactoryBase, the AddFooClient extension-method pattern), how to port legacy HttpWebRequest / WebClient (.NET Framework) code to this stack, and which 7.4.3 members are now soft-obsolete (IBetterHttpClientFactory, the BetterHttpClient shell, BetterHttpShellOptions, IBetterHttpFilter/Filters, AddGlobalHttpFilter/AddGlobalHttpHandler) and their native replacements. Use whenever application code registers or injects an HttpClient in a SnowBank-based app, declares a named client, configures user agents or HTTPS certificate validation, binds HTTP options from configuration, ports HttpWebRequest/.NET Framework 4.7.2 networking code to net8+/net10, or hits "You must register an implementation for INetworkMap"./snowbank-contractsHow to guard arguments and assert invariants with the Contract family in SnowBank.Core (namespace SnowBank.Diagnostics.Contracts): the argument guards (Contract.NotNull / NotNullOrEmpty / NotNullOrWhiteSpace / Positive / GreaterThan / GreaterOrEqual / LessThan / LessOrEqual / EqualTo / NotEqualTo / ValueNotNull) that validate a caller's arguments and throw ArgumentNullException / ArgumentException / ArgumentOutOfRangeException, versus the condition assertions (Contract.Requires / Assert / Ensures / Invariant / Fail) that check internal invariants and throw ContractException, plus the three compile levels (always-on Contract.X, Debug-only Contract.Debug.X, Paranoid.X under PARANOID_ANDROID), the CallerArgumentExpression auto-message, the nullable-flow and StackTraceHidden behavior, and the NUnit test integration. Use whenever code validates a method argument, replaces a hand-written `if (x == null) throw new ArgumentNullException(...)` or `Debug.Assert(...)` or `ArgumentNullException.ThrowIfNull(...)`, adds a precondition or state invariant, chooses between Contract, Contract.Debug and Paranoid, or hits a ContractException. Prefer these over raw throws and BCL asserts in SnowBank.Core / FoundationDB.Client code.Other plugins' skills for the same job