跳至正文
OpenAgentSkill
浏览已开放 · 目录记录日期 2026-11-21 · 自动更新和账户服务暂时关闭。
开发与测试

foundationdb-transactions

How 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

SnowBankSDK · 已有静态检查记录

安装与使用

运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。

npx skills add SnowBankSDK/foundationdb-dotnet-client --skill foundationdb-transactions

技能说明


name: foundationdb-transactions description: >- How 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.

FoundationDB .NET — Transactions & the Retry Loop

FoundationDB gives you serializable, ACID transactions over the whole keyspace. The catch: a transaction may conflict and need to be retried, and it has hard limits (time and size). The .NET client handles retries for you via a retry loop — but only if you use it correctly. The single biggest source of bugs is writing a transaction handler that is not safe to run more than once.

If you are encoding keys/values inside the transaction, read the foundationdb-keys-and-layers skill too.


1. Always use the retry loop

Don't manually BeginTransaction / CommitAsync in application code. Use the retryable methods on IFdbDatabase (or IFdbDatabaseProvider). Pick the narrowest one:

MethodTransaction typeUse for
db.ReadAsync(handler, ct)IFdbReadOnlyTransactionreads only; returns a result
db.WriteAsync(handler, ct)IFdbTransactionmutations that return nothing (the handler may still read — its transaction is a full read/write one)
db.ReadWriteAsync(handler, ct)IFdbTransactionmutations that must return a value out of the transaction

The split between WriteAsync and ReadWriteAsync is about the return value, not about whether you read. Both hand you a full IFdbTransaction. ReadWriteAsync has no "returns nothing" overload — if your handler returns no value, use WriteAsync.

// READ
Book? book = await db.ReadAsync(async tr =>
{
    var bytes = await tr.GetAsync(subspace.Key("D", id));
    return bytes.IsNull ? null : CrystalJson.Deserialize<Book>(bytes);
}, ct);

// WRITE (no reads, nothing to return)
await db.WriteAsync(tr =>
{
    tr.Set(subspace.Key("D", book.Id), FdbValue.ToJson(book));
}, ct);

// READ-MODIFY-WRITE (need a result and/or read before write)
long newBalance = await db.ReadWriteAsync(async tr =>
{
    long current = (await tr.GetAsync(accountKey)).ToInt64();
    long updated = current + amount;
    tr.Set(accountKey, FdbValue.ToFixed64LittleEndian(updated));
    return updated;
}, ct);

The retry loop commits for you (you never call CommitAsync inside the handler) and re-runs the handler on retryable errors until it succeeds, the CancellationToken fires, or a non-retryable error is thrown.

There is a state overload (db.ReadAsync(state, (tr, state) => …, ct)) that lets you pass captured data without allocating a closure — prefer it in hot paths.


2. THE rule: your handler must be idempotent

The handler lambda can and will run multiple times. Treat it as a pure function of the database state.

❌ Never mutate external/global state inside the handler. No incrementing in-memory counters, no adding to caches/lists, no logging "done", no sending messages, no static field writes. On a retry, those side effects happen again — but the earlier attempt's database writes were discarded.

✅ Do all such work after the loop returns successfully:

// WRONG — _cache is mutated even on attempts that never commit
await db.WriteAsync(tr => { tr.Set(k, v); _cache[id] = book; }, ct);

// RIGHT — only touch external state after the transaction has committed
await db.WriteAsync(tr => tr.Set(k, v), ct);
_cache[id] = book;

The handler may read whatever it needs from the transaction; it just must not affect anything outside it. (See also the success callback overloads, which run once after a successful commit.)

Native idempotency (fdb 7.2+) covers the commit-side hazard. A commit can fail with CommitUnknownResult: the client never learned whether it applied, so a blind retry of a read-modify-write could apply it twice. On a cluster at api level 720 or greater, tr.Options.WithAutomaticIdempotency() tags each commit so the cluster deduplicates it, and the retry loop returns the committed result instead of re-running the handler. It throws below api level 720; gate it on tr.Options.IsAutomaticIdempotencySupported if you also target older clusters. This does not replace the rule above: keep the handler side-effect-free, since native idempotency only makes the commit safe to retry.


3. Hard limits you must design around

LimitValueConsequence
Transaction lifetime5 secondsLong reads/range scans fail with past_version (error 1007). Don't iterate huge ranges in one tx.
Value size100,000 bytesSplit large blobs across keys (see FdbBlob).
Key size10,000 bytesKeep tuple keys reasonable.
Total writes per tx10,000,000 bytesBatch large imports across many transactions.

For bulk operations that exceed these, use the Fdb.Bulk.* helpers (import/export/batch) instead of one giant transaction, and the FdbKey.Batched(...) helpers to s

阅读完整来源 ↗