Key–value store
This API is available since Fedify 0.5.0.
The KvStore interface is a crucial component in Fedify, providing a flexible key–value storage solution for caching and maintaining internal data. This guide will help you choose the right KvStore implementation for your project and even create your own custom implementation if needed.
Choosing a KvStore implementation
Fedify offers several KvStore implementations to suit different needs.
Choose the implementation that best fits your project's requirements, considering factors like scalability, runtime environment, and distributed nature of your system.
MemoryKvStore
MemoryKvStore is a simple in-memory key–value store that doesn't persist data. It's best suited for development and testing environments where data don't have to be shared across multiple nodes. No setup is required, making it easy to get started.
Since Fedify 2.5.0, MemoryKvStore implements AtomicKvStore. Its atomic operations cover one MemoryKvStore instance in one process; they do not persist or coordinate state between instances. It imposes no fixed batch-count limit; available memory and runtime resources still bound each call.
Values are kept and returned by reference. Treat values passed to set(), setMany(), cas(), and casMany(), and values returned by reads or list(), as immutable. This also applies when you store the same object under several keys: mutating that object changes the value under every key without a store operation. getMany() captures the references at one point in time; it does not clone or freeze them. Inputs must be passive data; accessors, proxies, or other behavior that reenters the store during preparation or comparison are outside its supported domain. Persistent adapters serialize values and can support a different value domain, so test against your production adapter too.
- Best for
- Development and testing.
- Pros
- Simple, no setup required.
- Cons
- Data is not persistent, not suitable for production.
import { createFederation, MemoryKvStore } from "@fedify/fedify";
const federation = createFederation<void>({
kv: new MemoryKvStore(),
// ... other options
});SqliteKvStore
To use the SqliteKvStore, you need to install the @fedify/sqlite package first:
npm add @fedify/sqlitepnpm add @fedify/sqliteyarn add @fedify/sqlitebun add @fedify/sqlitedeno add jsr:@fedify/sqliteSqliteKvStore is a simple key–value store implementation that uses SQLite as the backend storage. It provides persistent storage with minimal configuration. It's suitable for development and testing. It uses native sqlite modules, node:sqlite for Node.js and Deno, bun:sqlite for Bun.
Since Fedify 2.5.0, SqliteKvStore implements AtomicKvStore across all keys in its configured table in one SQLite database. getMany() returns an input-ordered snapshot; writes, deletions and conditional batches commit together. Empty batches bypass the database. Mutation keys must be distinct, batches must be dense, and set(key, undefined) and TTLs on CAS deletion reject.
Nonempty batch operations and ordinary mutations require a writable connection outside caller-owned transactions. They reserve SQLite's writer slot even for snapshots and CAS mismatches. Busy errors can reject these calls, including when rollback-journal readers prevent completion; false means only a successfully completed comparison mismatch. Configure a caller-owned busy timeout if needed; the KV store does not retry or change connection settings. Ordinary get() and list() retain their single-statement behavior. Initialize outside caller transactions before using those ordinary reads there.
Values use JSON serialization and structural comparison of decoded stored values against raw expectations, ignoring object member order. Use decoded JSON shapes as expectations: a date becomes a string, and undefined object members disappear. TTLs share one millisecond-resolution cutoff and preserve representable fractional milliseconds. Nonpositive TTLs expire immediately; omitting a replacement TTL clears it. Calendar-dependent, nonfinite and out-of-range durations reject. There is no fixed batch-count limit, but memory, disk and SQLite limits still apply; an operation is never split into commits.
Use normal SQLite locking and journaling. Atomicity alone does not establish crash durability, which depends on connection settings and the filesystem. Concurrent WAL writes/checkpoints require the SQLite WAL-reset fix (3.51.3 or the 3.50.7/3.44.6 backports, or a verified equivalent fix). Bun 1.2.22's SQLite 3.50.4 is affected. SqliteMessageQueue enables WAL by default on shared database files, so the prerequisite also applies to combined KV and queue deployments. See the SQLite package README for the complete value, expiry, connection and durability restrictions.
- Best for
- Development and testing.
- Pros
- Simple, persistent with minimal configuration.
- Cons
- Limited scalability, not suitable for high-traffic production.
import { DatabaseSync } from "node:sqlite";
import { createFederation } from "@fedify/fedify";
import { SqliteKvStore } from "@fedify/sqlite";
const db = new DatabaseSync(":memory:");
const federation = createFederation<void>({
// ...
kv: new SqliteKvStore(db),
});import { Database } from "bun:sqlite";
import { createFederation } from "@fedify/fedify";
import { SqliteKvStore } from "@fedify/sqlite";
const db = new Database(":memory:");
const federation = createFederation<void>({
// ...
kv: new SqliteKvStore(db),
});import { DatabaseSync } from "node:sqlite";
import { createFederation } from "@fedify/fedify";
import { SqliteKvStore } from "@fedify/sqlite";
const db = new DatabaseSync(":memory:");
const federation = createFederation<void>({
// ...
kv: new SqliteKvStore(db),
});TIP
If you are using Bun, you may encounter a type error in your IDE because TypeScript's language server runs on Node.js and resolves the @fedify/sqlite module using Node.js conditional exports instead of Bun's. To fix this, add the following to your tsconfig.json:
{
"compilerOptions": {
"moduleResolution": "bundler",
"customConditions": ["bun"]
}
}This tells TypeScript to use Bun's module resolution when resolving conditional exports.
RedisKvStore
To use the RedisKvStore, you need to install the @fedify/redis package first:
npm add @fedify/redispnpm add @fedify/redisyarn add @fedify/redisbun add @fedify/redisdeno add jsr:@fedify/redisRedisKvStore is a key–value store implementation that uses Redis as the backend storage. It provides scalability and high performance, making it suitable for production use in distributed systems. It requires a Redis server setup and maintenance. It supports atomic ~KvStore.cas() on standalone Redis and Redis Cluster. CAS compares encoded bytes, so a custom Codec must encode equal values identically; with the default JSON codec, object property order matters. Redis must permit the EVAL command for CAS.
- Best for
- Production use, distributed systems.
- Pros
- Scalable, supports clustering.
- Cons
- Requires Redis setup and maintenance.
import { createFederation } from "@fedify/fedify";
import { RedisKvStore } from "@fedify/redis";
import Redis from "ioredis";
const redis = new Redis(); // Configure as needed
const federation = createFederation<void>({
kv: new RedisKvStore(redis),
// ... other options
});Atomic operations
Since Fedify 2.5.0, RedisKvStore implements AtomicKvStore on official Redis 7.2.17, 7.4.12, and 8.10.3. Other releases reject nonempty batch calls before reading or writing. Supporting another Redis release requires a new audit and Fedify update; ordinary single-key methods keep their existing compatibility. Modified engines, forks, script debugging, and module command hooks are not supported atomic configurations, and the version guard does not authenticate the server.
On standalone Redis, batches cover one selected database on the primary. On Cluster, all effective physical keys must share a slot in database zero. For a new namespace, the existing keyPrefix option can select that scope:
import { RedisKvStore } from "@fedify/redis";
import { Cluster } from "ioredis";
const redis = new Cluster([{ host: "127.0.0.1", port: 7000 }]);
const store = new RedisKvStore(redis, { keyPrefix: "{inventory}::" });
const values = await store.getMany([["available"], ["reserved"]]);Keys are not automatically tagged or moved. Changing a prefix selects a new namespace and needs an application migration for existing data. The first { and following } select a hash tag only if the pair is nonempty; an empty pair hashes the whole key. A tag in the ioredis client's own keyPrefix can take precedence over a tag in the adapter's keyPrefix. Cross-slot calls reject, including different slots on the same master; they never split into separate operations. Missing or expired keys can cause an entire batch to reject during resharding.
Each request is limited to 128 entries and 1 MiB of effective key, encoded values and expectations, and argument data, excluding the fixed script and protocol framing. Batch TTLs round up to whole seconds, with a minimum of one second and maximum of 2,147,483,647 seconds. Zero and negative TTLs therefore keep a value for one second. Omitting a TTL clears the previous expiry. Single-key TTLs keep their existing range handling. CAS compares encoded bytes; with the default JSON codec, object property order matters. Values must round-trip through their codec; undefined is never stored (as a CAS newValue it deletes the key), while null remains a value.
Before changing keys, the scripts read every target and check each write command's permissions. They require EVAL, GET or EXISTS, and the applicable SET, SETEX, or DEL access. Redis checks EVAL's read/write key access before entering the script, so key patterns must grant both read and write access even for getMany() snapshots. Snapshots route to the primary despite Cluster scaleReads. The existing Cluster prefix-listing SCAN limitation remains: listing does not reliably visit every node, and getMany() does not snapshot list().
Configured memory pressure can reject batch deletes as well as writes; ordinary delete() remains available. A successful batch is not a persistence or failover guarantee. ioredis can replay requests after disconnection, so even a CAS mismatch reply does not prove an earlier attempt never committed. Re-read and re-evaluate application rules after a mismatch or uncertain response. See the Redis package guide for codecs, supported configurations, limits, and retry behavior.
PostgresKvStore
To use the PostgresKvStore, you need to install the @fedify/postgres package first:
npm add @fedify/postgrespnpm add @fedify/postgresyarn add @fedify/postgresbun add @fedify/postgresdeno add jsr:@fedify/postgresPostgresKvStore is a key–value store implementation that uses PostgreSQL as the backend storage. It provides scalability and high performance, making it suitable for production use in distributed systems. It requires a PostgreSQL server setup and maintenance.
- Best for
- Production use, a system that already uses PostgreSQL.
- Pros
- Scalable, no additional setup required if already using PostgreSQL.
- Cons
- Requires PostgreSQL setup and maintenance.
import { createFederation } from "@fedify/fedify";
import { PostgresKvStore } from "@fedify/postgres";
import postgres from "postgres";
const federation = createFederation<void>({
kv: new PostgresKvStore(
postgres("postgresql://user:pass@localhost/db"),
),
// ... other options
});PostgreSQL atomic operations
This API is available since Fedify 2.5.0.
PostgresKvStore implements AtomicKvStore within one configured ordinary table or declarative partition, using the existing schema and PostgreSQL-representable Unicode string keys. Ordinary inheritance parents and children are unsupported for nonempty batches. Tables where row-level security is active for the current role are also rejected, because policies can filter individual mutations. getMany() returns one input-ordered snapshot; setMany() writes one batch; casMany() compares all expectations before applying any changes. JSON null remains distinct from missing or expired undefined.
Nonempty casMany() and deleteMany() with more than one key require a pool or a READ COMMITTED transaction-scoped Postgres.js client. Reserved clients reject those scopes before SQL; they still support ordinary methods, the single-statement batches, single-key deletion, and empty batches. Unsupported caller isolation rejects. Method presence does not certify a client's scope.
Caller-owned transactions must be used exclusively and sequentially throughout each atomic call, including initialization, every store wrapper, and raw SQL. Await each call before sending another command on that transaction: nested savepoints do not isolate overlapping calls. Success remains provisional until the outer commit, and successful batch locks remain held until then.
Mutating forms of cas() acquire the table write lock and use one server timestamp for comparison and the replacement's TTL origin. A cas() from undefined to undefined stays read-only. If a trigger skips a matching write, the call rejects and rolls back its database effects; false means only a comparison mismatch. cas() owns a transaction on pooled clients and uses a savepoint on transaction-scoped clients. Reserved clients use a savepoint inside an existing manual transaction or a transaction owned by the call. Caller transaction isolation is unchanged. Use reserved clients exclusively and sequentially during the call. CAS locks in caller-owned transactions remain until the outer commit, including after a mismatch.
Conditional batches and multi-key deletions acquire a table write lock before a fresh snapshot, protecting absent keys against ordinary and direct SQL writers. This serializes writes to the whole table and its descendants, and can interfere with autovacuum. A mismatch releases locks acquired in the batch savepoint; previous writes and setup may still hold locks. Prior caller writes can cause lock-upgrade deadlocks, requiring outer rollback before retry. Errors and configured lock timeouts reject; no automatic retry occurs.
The default JSON codec uses PostgreSQL jsonb equality: object member order is ignored, array order matters, Dates normalize to strings, and nonfinite numbers normalize to JSON null. Big integers, circular/unencodable values, NUL characters, and malformed Unicode reject. Irreversible value/JSON transforms are unsupported; identifier transforms remain usable. Raw SQL values must round-trip through the JavaScript JSON codec for CAS expectations.
TTLs retain PostgreSQL interval, session-timezone, and calendar semantics at microsecond precision, using one server expiry cutoff per operation. Omitting a replacement TTL clears expiry; zero durations expire immediately, and negative Temporal durations reject. A blocked write's TTL origin may precede its commit. Invalid JSON/TTL inputs reject even on mismatch. There is no fixed batch-count or key-length maximum; backend field, index, protocol, and memory limits apply without splitting. A physical index-size error arises on an attempted write; a mismatch does not attempt insertion, while a failed attempted write rolls back the batch.
Caller-owned batches with initialized: false repeat idempotent table setup and driver probing after possible outer rollback. Setup precedes the batch savepoint and its errors can abort the outer transaction. initialized: true keeps schema responsibility with the caller. Only pooled batches and cas() start best-effort cleanup after commit; logical expiry never depends on cleanup.
Atomic operations do not strengthen unlogged-table durability or override server WAL, synchronous_commit, storage, or replica settings. Lost responses can leave commit status unknown. See the package's atomic scope guide for the full client, codec, limit, and transaction contract.
PostgreSQL expiry index
This optimization is available since Fedify 2.5.0.
Expiry cleanup can use a B-tree expression index that stores a UTC-calendar expiration timestamp for each entry with a TTL. The index build populates keys for existing rows; no new table column, trigger, or separate backfill is needed. PostgreSQL maintains the index on every insert and update, including those from older Fedify versions.
With a pooled client, automatic initialization attempts to add the index to an empty table. It skips populated tables, tables with row-level security, and ordinary inheritance parents. It also skips index provisioning with initialized: true, a transaction client, or a reserved connection. Missing ownership, lock contention, or an index-build failure leaves the store usable without the optimization. Ordinary table initialization still follows the existing initialized and unlogged options.
For an existing table, or when you manage DDL yourself, run this migration as the table owner, outside a transaction block. Replace public.fedify_kv_v2 with your actual schema and table, and choose an unused index name in that schema. Quote mixed-case or special identifiers, for example "Cache"."Federation keys". Use the literal 'UTC' in both function calls:
CREATE INDEX CONCURRENTLY fedify_kv_expiry
ON public.fedify_kv_v2
((timezone('UTC', timezone('UTC', created) + ttl)))
WHERE ttl IS NOT NULL;
ANALYZE public.fedify_kv_v2;The concurrent build permits ordinary writes while it runs, but needs time, disk space, and database resources. ANALYZE collects expression statistics so the planner can choose the index when few or no entries have expired. If the role lacks privileges, PostgreSQL skips ANALYZE with only a warning, so run it as a role allowed to analyze the table. Keep normal autovacuum and analyze maintenance enabled as the table grows.
The index can be created before or after an application upgrade. Old and new versions can share the table, and downgrading does not require removing the index. Without the index, the new cleanup query remains correct but may scan the full table. An index also adds write and storage costs, including fewer opportunities for HOT updates. Once the index exists, a write whose expiration timestamp falls outside PostgreSQL's supported timestamp range fails atomically, including writes from older application versions. An existing overflowing row can also prevent index creation; correct such data before retrying the migration.
Logical TTL checks in get(), list(), and cas() still evaluate created + ttl in the connection's TimeZone. Cleanup uses the UTC index to find candidates and rechecks that original predicate before deleting them. This preserves PostgreSQL's calendar-month, calendar-day, and DST behavior. For calendar intervals in a non-UTC session, a different UTC-calendar result can delay physical deletion or make cleanup visit a candidate before it logically expires; the recheck prevents early deletion. Reads and CAS still observe the original logical expiry. Cleanup's 1,000-row limit bounds the rows selected and deleted, not the index entries examined.
For traditional inheritance, build the index and run ANALYZE on the parent and on each child, including children added later. An index on the parent does not cover inherited children.
For a populated partitioned table, PostgreSQL does not support CREATE INDEX CONCURRENTLY on the parent. Create the parent index with CREATE INDEX ... ON ONLY, build matching indexes concurrently on each leaf, and attach them with ALTER INDEX ... ATTACH PARTITION. Repeat the parent and attachment steps at each intermediate partitioning level. After all attachments, verify that the root index is valid, then run ANALYZE on the root and each leaf partition. Autovacuum does not analyze partitioned parents. New partitions then receive matching indexes automatically. See PostgreSQL's partitioned index procedure for the full workflow.
A failed concurrent build can leave an invalid index. Inspect its state:
SELECT indexrelid::regclass AS index_name, indisvalid
FROM pg_index
WHERE indrelid = 'public.fedify_kv_v2'::regclass
AND NOT indisprimary;After confirming that an invalid index is the one created by your migration, run DROP INDEX CONCURRENTLY <schema>.<index_name> outside a transaction. Replace <schema> and <index_name> with the schema and index name you chose for the migration, quoting each identifier as needed. Then rerun the index build, followed by ANALYZE. Automatic initialization never replaces conflicting or invalid indexes. It accepts an existing valid, non-unique, single-attribute B-tree index if it uses the expression above or its AT TIME ZONE equivalent, and has either no predicate or WHERE ttl IS NOT NULL.
PgliteKvStore
This API is available since Fedify 2.4.0.
To use the PgliteKvStore, install the @fedify/pglite package and PGlite:
npm add @fedify/pglite @electric-sql/pglitepnpm add @fedify/pglite @electric-sql/pgliteyarn add @fedify/pglite @electric-sql/pglitebun add @fedify/pglite @electric-sql/pglitedeno add jsr:@fedify/pglite npm:@electric-sql/pglitePgliteKvStore uses an embedded PGlite database without requiring a PostgreSQL server. It uses the same schema and default table name as PostgresKvStore, so data can be migrated to PostgreSQL without converting the key–value records.
- Best for
- Development and testing, single-process deployments, and embedded or desktop applications that need PostgreSQL-compatible storage without a PostgreSQL server.
- Pros
- No server installation, PostgreSQL-compatible SQL, and the same schema as
PostgresKvStore. - Cons
- Only one process and PGlite instance can open a data directory, data are not shared between processes, and horizontal scaling is not supported.
import { PGlite } from "@electric-sql/pglite";
import { createFederation } from "@fedify/fedify";
import { PgliteKvStore } from "@fedify/pglite";
const pg = new PGlite("./data/fedify");
const federation = createFederation<void>({
kv: new PgliteKvStore(pg),
// ... other options
});WARNING
The caller owns the PGlite instance and must close it during application shutdown after pending store operations finish. Do not open the same data directory from multiple worker processes. Use one PGlite instance per data directory and runtime isolate.
Since Fedify 2.5.0, this store also implements AtomicKvStore. Each snapshot or batch uses one PGlite transaction and one expiry cutoff. Wrappers must share one normal PGlite owner and table. Do not call the store inside the owner's transaction callback or bypass its query queue with raw protocol or manual transaction control. Worker proxies and browser persistence are outside the documented atomic scope.
CAS compares JSONB values: object member order is ignored, array order matters, and stored null differs from absence. Keys must be nonempty arrays of well-formed Unicode strings without U+0000. Negative TTLs, timestamp overflow, and TTLs on CAS deletion reject; zero TTL expires immediately. Intervals round to microseconds and calendar units follow the session time zone. There is no fixed batch-entry cap. Engine key insertion limits depend on compression; a mismatch does not prove that unattempted writes would fit. Statement failures roll back the batch; commit or post-commit synchronization failures can reject after changes have committed. Long batches occupy the shared instance. Nonempty mutation calls await the owner's syncToFs() after transaction completion, including read-only CAS mismatches. Backend failures reject instead of returning false; any committed mutations remain applied. Atomic execution does not establish crash durability. See the package's atomic-operation guidance for codecs, legacy-row recovery, and the owner's synchronization policy.
MysqlKvStore
This API is available since Fedify 2.1.0.
To use the MysqlKvStore, you need to install the @fedify/mysql package first:
npm add @fedify/mysql mysql2pnpm add @fedify/mysql mysql2yarn add @fedify/mysql mysql2bun add @fedify/mysql mysql2deno add jsr:@fedify/mysqlMysqlKvStore is a key-value store implementation that uses MySQL (or MariaDB) as the backend storage. It provides scalability and high performance, making it suitable for production use in distributed systems. It requires a MySQL or MariaDB server setup and maintenance.
- Best for
- Production use, a system that already uses MySQL or MariaDB.
- Pros
- Scalable, no additional setup required if already using MySQL/MariaDB.
- Cons
- Requires MySQL/MariaDB setup and maintenance.
import { createFederation } from "@fedify/fedify";
import { MysqlKvStore } from "@fedify/mysql";
import mysql from "mysql2/promise";
const pool = mysql.createPool("mysql://user:pass@localhost/db");
const federation = createFederation<void>({
kv: new MysqlKvStore(pool),
// ... other options
});Since Fedify 2.5.0, MysqlKvStore implements AtomicKvStore, with atomic snapshots and conditional batches across keys in one primary database/table. It uses InnoDB transactions with explicit REPEATABLE READ, including for single-key reads and CAS. Use getMany() for a snapshot and casMany() to compare every expectation before committing all replacements or deletions. A mismatch returns false; reread and re-evaluate before retrying.
The adapter validates its InnoDB schema even with initialized: true, which skips DDL but requires metadata visibility. Use the default schema, a normal mysql2 pool with autocommit enabled and default object/type decoding, and the same fixed-offset or UTC session time_zone across clients. Caller-owned transactions, replica routing, NO_BACKSLASH_ESCAPES, custom decoding, and schema changes during use are unsupported. Values use JSON conversion and decoded structural equality; set(key, undefined) rejects. Batches have at most 1,000 input entries, and serialized keys at most 768 Unicode code points. TTLs are truncated to safe integer microseconds, approximately ±285 years; omitting a replacement TTL clears its previous expiry.
Deadlocks and MariaDB snapshot conflicts retry with fresh comparisons, up to five total attempts. Other backend failures reject, and a lost commit response can leave the outcome unknown. Cleanup runs after commit; its failures are logged, while logical expiry always applies. See the MySQL package README for schema, codec, clock, cleanup and resource restrictions.
DenoKvStore (Deno only)
WARNING
DenoKvStore is deprecated since Fedify 2.5.0. Deno's team is joining Cloudflare, and Deno KV is built primarily for Deno Deploy, which is shutting down. Fedify keeps supporting @fedify/denokv throughout the 2.x series, but the package will be removed in Fedify 3.0.0. Use SqliteKvStore for local or single-node deployments, PostgresKvStore, RedisKvStore, or MysqlKvStore for production, or WorkersD1KvStore if you move to Cloudflare Workers. See #1336 for the removal plan.
To use the DenoKvStore, you need to install the @fedify/denokv package first:
deno add jsr:@fedify/denokvDenoKvStore is a key–value store implementation for Deno runtime that uses Deno's built-in Deno.openKv() API. It provides persistent storage and good performance for Deno environments. It can be used in existing Deno applications.
- Best for
- Existing Deno applications. Not recommended for new projects.
- Pros
- Persistent storage, good performance, easy to set up.
- Cons
- Only available in Deno runtime, and deprecated since Fedify 2.5.0.
import { createFederation } from "@fedify/fedify";
import { DenoKvStore } from "@fedify/denokv";
const kv = await Deno.openKv();
const federation = createFederation<void>({
kv: new DenoKvStore(kv),
// ... other options
});WorkersD1KvStore (Cloudflare Workers only)
This API is available since Fedify 2.5.0.
To use the WorkersD1KvStore, you need to install the @fedify/cfworkers package first:
deno add jsr:@fedify/cfworkersnpm add @fedify/cfworkerspnpm add @fedify/cfworkersyarn add @fedify/cfworkersbun add @fedify/cfworkersWorkersD1KvStore is a key–value store implementation for Cloudflare Workers that uses Cloudflare D1, Cloudflare's serverless SQL database. Fedify writes to its key–value store about as often as it reads from it, and some of its records, such as idempotency records and signature nonces, need strong consistency. D1 fits this workload better than Cloudflare Workers KV, which is tuned for read-heavy workloads and is eventually consistent. WorkersD1KvStore implements AtomicKvStore, including single-key CAS, snapshot reads and conditional multi-key writes.
- Best for
- Production use in Cloudflare Workers environments.
- Pros
- Persistent storage, primary reads and atomic multi-key operations.
- Cons
- Only available in Cloudflare Workers runtime.
import type { Federation } from "@fedify/fedify";
import { WorkersD1KvStore } from "@fedify/cfworkers";
export default {
async fetch(request, env, ctx) {
const federation: Federation<void> = await builder.build({
// The table is created by a D1 migration; see below:
kv: new WorkersD1KvStore(env.DB, { initialized: true }),
});
return await federation.fetch(request, { contextData: undefined });
}
} satisfies ExportedHandler<{ DB: D1Database }>;The store keeps its entries in a table named fedify_kv by default, which you can change with the tableName option. Without initialized: true, each store instance creates and checks its schema on first use. The names <tableName>_atomic and idx_<tableName>_expires are reserved for the guard table and expiry index; table names ending in _atomic are rejected. The entry table must have a single-column key primary index using BINARY collation, so differently cased keys remain distinct. Automatic initialization rejects incompatible primary indexes. Key lookups, mutations, and listing explicitly use binary comparisons even if the column declares another collation.
Create both tables and the index with a D1 migration in production, then pass initialized: true to avoid repeated schema queries:
CREATE TABLE IF NOT EXISTS fedify_kv (
key TEXT PRIMARY KEY NOT NULL,
value TEXT NOT NULL,
expires INTEGER
);
CREATE INDEX IF NOT EXISTS idx_fedify_kv_expires ON fedify_kv (expires);
CREATE TABLE IF NOT EXISTS fedify_kv_atomic (
singleton INTEGER PRIMARY KEY,
cutoff INTEGER NOT NULL,
matched INTEGER NOT NULL
);Atomic operations cover all keys in one configured table in one D1 database. getMany() reads one snapshot and preserves input order, missing values and duplicate keys. setMany(), deleteMany() and casMany() commit each batch as a unit; casMany() compares every expectation before changing any entry. Single-key set() and cas() use the same guard protocol. Each nonempty set or CAS writes and removes a private guard row, including absence-only CAS. A mismatch leaves all user values and TTLs unchanged. Backend errors reject, and a lost response can leave commit status unknown. Re-read and re-evaluate the application rule after a mismatch; include a non-reused version in values if ABA changes must be detected.
Values use JSON.stringify() and JSON.parse(). During serialization, JSON.stringify() coerces nonfinite numbers to null. Object members with undefined, function, or symbol values are omitted; in arrays, those elements become null. Top-level undefined is only an absence/deletion sentinel in CAS; it cannot be stored. Serialization rejects when JSON.stringify() returns undefined or throws. Cycles and BigInt values need a custom JSON serialization. CAS compares the persisted JSON structurally, ignoring object member order while retaining array order and types. Values deeper than SQLite's 1,000-level JSON limit use exact serialized comparison instead. External guard writes, triggers and custom constraints that alter the protocol, and raw JSON rows with duplicate object members, are unsupported.
TTLs use one database-clock cutoff per operation and are truncated to integer milliseconds. Nonpositive durations, including positive durations shorter than one millisecond after truncation, expire immediately. Durations whose absolute total exceeds 8.64e15 milliseconds, nonfinite totals, and calendar durations requiring a reference date reject. Replacing without a TTL clears the previous expiry. Successful sets and CAS also purge up to 100 entries expired at the same cutoff; a mismatch does not run that cleanup.
Snapshots accept up to 256 input keys, counting duplicates. Their separate 8 MiB byte budget counts encoded keys and values once per unique, live row; missing and expired keys contribute no bytes to that budget. For maximum-size values, the byte budget usually binds first. Mutations accept up to 128 entries and 16 MiB of encoded keys, expectations and replacements combined. Each encoded key/value row and each bound string is limited to 1,999,000 UTF-8 bytes. getMany() and deleteMany() keys also have a 1,999,000-byte aggregate encoded-key limit, and the final escaped JSON key payload must fit the same limit. Oversized operations reject without splitting; backend or runtime limits can also reject smaller calls.
WARNING
Pass the D1Database binding itself (e.g., env.DB) to get strongly consistent reads. WorkersD1KvStore also accepts a D1 session created with D1Database.withSession(), but sessions only provide sequential consistency and can read stale data from a replica, which can make Fedify process the same activity twice.
NOTE
Since your D1Database is not bound to a global variable, but rather passed as an argument to the fetch() method, you need to instantiate your Federation object inside the fetch() method, rather than the top level. See the Builder pattern for structuring section for details.
WorkersKvStore (Cloudflare Workers only)
This API is available since Fedify 1.6.0.
To use the WorkersKvStore, you need to install the @fedify/cfworkers package first:
npm add @fedify/cfworkerspnpm add @fedify/cfworkersyarn add @fedify/cfworkersbun add @fedify/cfworkersdeno add jsr:@fedify/cfworkersWorkersKvStore is a key–value store implementation for Cloudflare Workers that uses Cloudflare's built-in Cloudflare Workers KV API. It provides persistent storage with fast reads for Cloudflare Workers environments.
However, Workers KV is tuned for read-heavy workloads and is eventually consistent, while Fedify writes to its key–value store about as often as it reads from it. It also does not support ~KvStore.cas(), so some features fall back to non-atomic code paths, and others, such as forwarding activities to the other gateways of FEP-ef61 portable inboxes, are unavailable. For new Cloudflare Workers deployments, prefer WorkersD1KvStore.
- Best for
- Existing Cloudflare Workers applications that already use Workers KV.
- Pros
- Persistent storage, fast reads, easy to set up.
- Cons
- Only available in Cloudflare Workers runtime, eventually consistent, priced for read-heavy workloads, and does not support
~KvStore.cas().
import type { Federation } from "@fedify/fedify";
import { WorkersKvStore } from "@fedify/cfworkers";
export default {
async fetch(request, env, ctx) {
const federation: Federation<void> = await builder.build({
kv: new WorkersKvStore(env.KV_BINDING),
});
return await federation.fetch(request, { contextData: undefined });
}
} satisfies ExportedHandler<{ KV_BINDING: KVNamespace<string> }>;NOTE
Since your KVNamespace is not bound to a global variable, but rather passed as an argument to the fetch() method, you need to instantiate your Federation object inside the fetch() method, rather than the top level.
For better organization, you probably want to use a builder pattern to register your dispatchers and listeners before instantiating the Federation object. See the Builder pattern for structuring section for details.
NetlifyBlobsKvStore
This API is available since Fedify 2.4.0.
To use the NetlifyBlobsKvStore, you need to install @fedify/netlify and @netlify/blobs.
npm add @fedify/netlify @netlify/blobspnpm add @fedify/netlify @netlify/blobsyarn add @fedify/netlify @netlify/blobsbun add @fedify/netlify @netlify/blobsdeno add jsr:@fedify/netlify npm:@netlify/blobsNetlifyBlobsKvStore from @fedify/netlify stores federation state in Netlify Blobs without requiring a separate database. It supports expiration, prefix listing, and atomic compare-and-set (CAS) operations.
- Best for
- Small Fedify applications on Netlify Functions.
- Pros
- Persistent storage and atomic CAS without a separate database.
- Cons
- 600-byte encoded key limit; expired blobs and tombstones are not automatically removed.
import { createFederation } from "@fedify/fedify";
import { NetlifyBlobsKvStore } from "@fedify/netlify";
import { getStore } from "@netlify/blobs";
const federation = createFederation<void>({
kv: new NetlifyBlobsKvStore(getStore({
name: "fedify",
consistency: "strong",
})),
});CAS operations always use strong reads and conditional writes. Configuring the Blobs store with consistency: "strong" also enables strong consistency for ordinary reads and listings.
NOTE
If your Netlify application already uses PostgreSQL, you can use PostgresKvStore from @fedify/postgres instead. Netlify Blobs is optional; choose the store that matches your application's storage setup.
Atomic operations across keys
This API is available since Fedify 2.5.0.
Use AtomicKvStore when related values must be read or changed together. It extends KvStore with required cas(), getMany(), setMany(), deleteMany(), and casMany() methods. These methods remain optional on ordinary KvStore implementations.
Check an application-provided store with isAtomicKvStore() before using this capability. The guard checks that all five methods are functions; it cannot verify their atomicity, durability, or supported key scope. For example, reserve a record and decrement its budget together:
import { isAtomicKvStore, type KvStore } from "@fedify/fedify";
async function reserve(store: KvStore, reservationId: string): Promise<boolean> {
if (!isAtomicKvStore(store)) {
throw new TypeError("This operation requires an AtomicKvStore");
}
const reservationKey = ["example", "reservation", reservationId] as const;
const budgetKey = ["example", "remaining-budget"] as const;
const [reservation, budget] = await store.getMany([
reservationKey,
budgetKey,
]);
if (reservation !== undefined || typeof budget !== "number" || budget <= 0) {
return false;
}
return await store.casMany([
{ key: reservationKey, expectedValue: undefined, newValue: true },
{ key: budgetKey, expectedValue: budget, newValue: budget - 1 },
]);
}Initialize the budget separately. If the conditional commit returns false, read again and re-evaluate the application's eligibility rule before retrying. Reusing an earlier decision with newly read values can admit work that no longer qualifies.
Operation semantics
getMany() returns an array in input order from one consistent read point, including its logical expiry checks. Duplicate read keys repeat the same snapshot value. Missing or expired entries are undefined; stored null remains null. The snapshot covers the requested keys, not key discovery through list().
setMany() replaces every supplied value in one unconditional operation. deleteMany() removes every supplied key in one operation. casMany() compares all expectations against the same state before applying any change; one mismatch returns false and changes nothing, including existing TTLs. Single-key cas() follows the same comparison and value rules.
In conditional operations, expectedValue: undefined means the key must be absent, and newValue: undefined means deletion. Deletion removes the entry from list() too. set() and setMany() reject undefined on an AtomicKvStore; skip the write to preserve the former no-op, or use delete() or deleteMany() for unconditional removal. For conditional removal, use cas() or casMany() with newValue: undefined and omit the TTL.
Each set or conditional entry can supply its own options.ttl:
await store.setMany([
{ key: ["example", "budget"], value: 10 },
{
key: ["example", "temporary-label"],
value: "ready",
options: { ttl: Temporal.Duration.from({ minutes: 5 }) },
},
]);
await store.deleteMany([
["example", "retired-label"],
["example", "retired-budget"],
]);A successful replacement without a TTL removes the previous TTL. A logically expired key is absent even if the backend has not physically reclaimed it. A deletion with a non-null options.ttl is invalid, including when another expectation would mismatch; empty options are valid. MemoryKvStore preserves precision below one hour and treats zero or negative TTLs as immediately expired. It rejects calendar durations that require a relative date. Other adapters must document their duration support and expiry precision; RedisKvStore's current single-key operations round up to whole seconds.
Batch arrays with missing elements (sparse arrays) are invalid. Mutation batches reject duplicate keys before writing, including keys expressed by separate arrays with identical string components. Empty reads return []; empty writes and deletes do nothing; an empty casMany() returns true. Invalid input, unsupported scope, size limits, and backend failures are errors. false means only a proven comparison mismatch. MemoryKvStore reports validation errors through rejected promises, including its single-key methods. Adapters must reject an unsupported atomic call rather than split it into smaller commits.
Equality and supported values depend on the adapter, and must agree between cas() and casMany(). MemoryKvStore uses structural comparison, with object member order ignored. RedisKvStore.cas() compares encoded bytes, so its default JSON codec treats object member order as significant. JSON-backed adapters cannot represent every JavaScript value that MemoryKvStore accepts. Follow the adapter's documented codec rules when preparing expected values.
Each call is atomic within the adapter's documented backend scope. Separate calls do not form a transaction, and atomic execution alone does not establish crash durability or exactly-once external effects. To detect a value that changes and changes back (the ABA problem), include a non-reused version in the value. A lost response can leave commit status unknown; use a version check or an operation receipt before repeating effects.
Current support
The table below shows which stores implement AtomicKvStore and the scope each one covers. Single-key CAS support does not imply atomic multi-key support.
| Implementation | AtomicKvStore | Scope and limits |
|---|---|---|
MemoryKvStore | Yes | Development and testing only; one instance. |
PostgresKvStore | Yes | One table; client and transaction restrictions apply. |
RedisKvStore | Yes | Official Redis 7.2.17, 7.4.12, or 8.10.3; standalone or one Cluster slot; up to 128 entries and 1 MiB per call. |
PgliteKvStore | Yes | One PGlite owner and table; JSONB comparison. |
SqliteKvStore | Yes | One configured table in one database; writable handles, JSON values. |
MysqlKvStore | Yes | InnoDB; one table in one primary database, up to 1,000 entries per operation. |
DenoKvStore | No | Deprecated since 2.5.0. |
NetlifyBlobsKvStore | No | Single-key CAS only. |
WorkersKvStore | No | No CAS; cannot implement this contract with Workers KV. |
WorkersD1KvStore | Yes | One configured table in one D1 database; codec, TTL, size and session restrictions apply. |
Bounding how long cache entries live
This section is relevant since Fedify 2.4.0.
Fedify keeps two caches in your KvStore: cached actor public keys and remembered per-origin HTTP Message Signatures specs. Since Fedify 2.4.0 both are written with a time-to-live, so a KvStore that never sees an explicit clear no longer accumulates entries for actors and origins that have stopped federating. The defaults are 30 days for cached keys and 90 days for remembered specs, and applications can override them through publicKeyTtl and httpMessageSignaturesSpecTtl:
import { createFederation, MemoryKvStore } from "@fedify/fedify";
const federation = createFederation<void>({
kv: new MemoryKvStore(),
publicKeyTtl: { days: 7 },
httpMessageSignaturesSpecTtl: { days: 30 },
});Both TTLs are a retention tradeoff, not a free cleanup knob. A shorter TTL keeps less in the store and bounds how long a revoked or rotated key or an outdated spec stays cached, but every expiry costs a request to the remote server: verification has to refetch the key, and delivery has to relearn the spec by double-knocking again. That refetch is not guaranteed to succeed—if the peer is down, unreachable, or has removed the actor when the entry expires, verification fails where it would have succeeded from cache. Lengthening a TTL inverts the tradeoff: fewer remote requests and more tolerance of unavailable peers, at the cost of holding stale entries longer.
Pick the shorter end when your store is under space pressure or you need revoked keys to fall out quickly, and the longer end when you federate with peers that are frequently unavailable.
Clearing legacy cache entries
This section is relevant since Fedify 2.4.0.
Entries written by Fedify 2.3 or earlier have no TTL. They are not migrated or expired automatically: they simply stay in your KvStore until something overwrites them, which is the same behavior Fedify has always had. Leaving them alone is a perfectly valid choice—Fedify keeps serving and refreshing them as before, and they get a TTL the next time they are written.
If you would rather not wait for that, you can clear the old entries yourself. Both caches live under their kvPrefixes entries, which are ["_fedify", "publicKey"] and ["_fedify", "httpMessageSignaturesSpec"] by default:
publicKey— cached actor public keyshttpMessageSignaturesSpec— remembered HTTP Message Signatures specs
These are defaults, not fixed values. If you passed your own kvPrefixes to createFederation(), substitute your prefixes for _fedify, publicKey, and httpMessageSignaturesSpec in every example below. The same goes for the adapter-level namespacing described in each subsection: RedisKvStore prepends its own keyPrefix, and PostgresKvStore stores rows in its own tableName.
Clearing these entries costs the remote requests described in the previous section: the caches are soft state that Fedify relearns on demand, but every cleared key has to be refetched before it can be used again, and that refetch fails while the peer is unavailable. Apply these cleanup procedures only to the cache prefixes. Authoritative application state, such as budgets, reservations, or replay cutoffs, needs its own retention and recovery rules; it cannot be reconstructed by refetching a peer. Prefer clearing them while your peers are reachable, and clear only the prefixes you actually need to reclaim.
Clearing entries in RedisKvStore
RedisKvStore stores every key under a shared prefix ("fedify::" by default, configurable via RedisKvStoreOptions.keyPrefix), followed by the KvKey parts joined with "::". Collect the whole scan result before deleting anything—deleting keys while --scan is still iterating can make the cursor skip entries:
for pattern in 'fedify::_fedify::publicKey::*' \
'fedify::_fedify::httpMessageSignaturesSpec::*'; do
redis-cli --scan --pattern "$pattern" > /tmp/fedify-keys.txt
test -s /tmp/fedify-keys.txt && xargs -a /tmp/fedify-keys.txt redis-cli del
rm -f /tmp/fedify-keys.txt
doneReplace the leading fedify:: with your own keyPrefix if you configured a custom one, and the _fedify::publicKey and _fedify::httpMessageSignaturesSpec parts with your own kvPrefixes.
Clearing entries in PostgresKvStore
PostgresKvStore stores every entry as a row keyed by a text[] column (the table is named fedify_kv_v2 by default, configurable via PostgresKvStoreOptions.tableName). Delete the two Fedify caches with:
DELETE FROM fedify_kv_v2
WHERE array_length(key, 1) >= 2 AND key[1:2] = ARRAY['_fedify', 'publicKey'];
DELETE FROM fedify_kv_v2
WHERE array_length(key, 1) >= 2
AND key[1:2] = ARRAY['_fedify', 'httpMessageSignaturesSpec'];Replace fedify_kv_v2 with your own tableName if you configured a custom one, and the array literals with your own kvPrefixes.
Clearing entries in other KvStore implementations
For any other KvStore, iterate the two prefixes with ~KvStore.list(), collect the keys, and delete them afterwards. Deleting while the iterator is still open can make an implementation skip entries, the same way it does with redis-cli --scan:
const prefixes: KvKey[] = [
["_fedify", "publicKey"],
["_fedify", "httpMessageSignaturesSpec"],
];
for (const prefix of prefixes) {
const keys: KvKey[] = [];
for await (const entry of kv.list(prefix)) keys.push(entry.key);
for (const key of keys) await kv.delete(key);
}Substitute your own kvPrefixes for the two prefixes if you configured them.
Implementing a custom KvStore
TIP
We are always looking to improve Fedify and add more KvStore implementations. If you've created a custom implementation that you think would be useful to others, consider contributing it to the community by packaging it as a standalone module and sharing it on JSR and npm.
If the provided implementations don't meet your needs, you can create a custom KvStore. Here's a step-by-step guide:
Implement the KvStore interface
Create a class that implements the KvStore interface. The interface defines four required methods: get(), set(), delete(), and list(). cas(), getMany(), setMany(), deleteMany(), and casMany() are optional. Implement all five with the contract below when your store supports AtomicKvStore; ordinary stores need not implement them.
import type {
KvStore,
KvKey,
KvStoreSetOptions,
KvStoreListEntry,
} from "@fedify/fedify";
class MyCustomKvStore implements KvStore {
async get<T = unknown>(key: KvKey): Promise<T | undefined> {
// Implement get logic
}
async set(
key: KvKey,
value: unknown,
options?: KvStoreSetOptions
): Promise<void> {
// Implement set logic
}
async delete(key: KvKey): Promise<void> {
// Implement delete logic
}
async cas(
key: KvKey,
expectedValue: unknown,
newValue: unknown
): Promise<boolean> {
// Implement compare-and-swap logic if needed
}
async *list(prefix?: KvKey): AsyncIterable<KvStoreListEntry> {
// Implement list logic
}
}Handle KvKey
The KvKey is an array of strings. You'll need to convert it into a format suitable for your storage backend. For example:
private serializeKey(key: KvKey): string {
return key.join(':');
}
NOTE
The above example uses a simple colon-separated string as the serialized key, but in practice, it probably needs to be more sophisticated to handle complex keys and avoid conflicts.
Implement get() method
Retrieve the value associated with the key. Remember to handle cases where the key doesn't exist. Return undefined only for a missing key; null is a valid stored value:
async get<T = unknown>(key: KvKey): Promise<T | undefined> {
const serializedKey = this.serializeKey(key);
// Retrieve value from your storage backend
const value = await this.storage.retrieve(serializedKey);
return value as T | undefined;
}
Implement set() method
Store the value with the given key. Handle the optional TTL if your backend supports it:
async set(
key: KvKey,
value: unknown,
options?: KvStoreSetOptions,
): Promise<void> {
const serializedKey = this.serializeKey(key);
if (options?.ttl == null) {
await this.storage.set(serializedKey, value);
} else {
// Set with TTL if supported
await this.storage.setWithTtl(
serializedKey,
value,
options.ttl.total('millisecond'),
);
}
}
Implement delete() method
Remove the value associated with the key:
async delete(key: KvKey): Promise<void> {
const serializedKey = this.serializeKey(key);
await this.storage.remove(serializedKey);
}
Implement list() method
This API is available since Fedify 1.10.0.
Since Fedify 2.0.0, this method is required instead of optional.
The list() method allows you to enumerate all entries whose keys start with a given prefix. This is useful for implementing batch operations or iterating over related entries. If your storage backend supports prefix scanning, you can use it to implement this method efficiently.
async *list(prefix?: KvKey): AsyncIterable<KvStoreListEntry> {
const serializedPrefix = prefix ? this.serializeKey(prefix) : "";
for await (const { key, value } of this.storage.scan(serializedPrefix)) {
yield {
key: this.deserializeKey(key),
value,
};
}
}
The list() method takes an optional prefix parameter specifying the key prefix to filter by. If omitted or empty, it returns all entries. It returns an AsyncIterable of KvStoreListEntry objects, each containing a key and a value.
TIP
When implementing list(), make sure to:
- Include the exact prefix key itself if it exists (not just keys that have additional components after the prefix)
- Filter out expired entries if your storage backend supports TTL
- Handle pagination efficiently for large datasets
Implement the AtomicKvStore interface
Implement all five atomic methods in addition to the ordinary store methods. Use the exported entry types for the batch signatures:
import type {
AtomicKvStore,
KvKey,
KvStoreCasEntry,
KvStoreSetEntry,
} from "@fedify/fedify";
interface AtomicMethods {
getMany<T = unknown>(keys: readonly KvKey[]): Promise<(T | undefined)[]>;
setMany(entries: readonly KvStoreSetEntry[]): Promise<void>;
deleteMany(keys: readonly KvKey[]): Promise<void>;
casMany(entries: readonly KvStoreCasEntry[]): Promise<boolean>;
cas: AtomicKvStore["cas"];
}Document the supported value domain, comparison, TTL precision, atomic key scope, batch limits, and durability for your adapter. Apply the stronger set(key, undefined) rejection rule to single-key set() too. Legacy optional CAS implementations can differ in deletion or TTL validation; audit them before claiming the full contract.
SqliteKvStore reserves the database's writer transaction before capturing its expiry cutoff and rejects read-only handles. Its per-key statements share one transaction, so an error rolls back the complete call, including initialization and expiry cleanup.
Validate and encode the complete input before the first mutation. Check structural duplicate keys and invalid deletion TTLs even if a conditional comparison would fail. Runtime validation must reject unsupported inputs without partially changing earlier entries.
Implement ~AtomicKvStore.cas() method
The cas() method atomically updates a value only if it matches the expected value. It is required on AtomicKvStore and remains optional on KvStore. Use a backend conditional write or a transaction that protects both existing and absent keys against competing clients. An unlocked read followed by a write is insufficient.
The following example illustrates delegation of single-key CAS only. The hypothetical backend must provide the comparison, logical expiry, deletion, and validation guarantees described above; the wrapper does not establish them. Implement the other four methods before declaring AtomicKvStore.
async cas(
key: KvKey,
expectedValue: unknown,
newValue: unknown,
options?: KvStoreSetOptions
): Promise<boolean> {
const serializedKey = this.serializeKey(key);
return await this.storage.compareAndSwap(
serializedKey,
expectedValue,
newValue,
options
);
}
Implement ~AtomicKvStore.getMany() method
Use a backend snapshot read that includes all requested keys and one expiry cutoff. Preserve input order, duplicates, and missing entries when arranging the results. Several ordinary reads, even inside a transaction, need the appropriate snapshot or isolation guarantees. Promise.all() over get() calls does not establish a consistent snapshot.
Implement ~AtomicKvStore.setMany() and ~AtomicKvStore.deleteMany() methods
Run the complete mutation within one supported transaction or atomic backend operation. Apply each entry's TTL with its replacement, and remove old TTLs when no new TTL is supplied. Reject unsupported batches before any mutation; do not split calls to fit backend limits. If a later statement fails, roll back all earlier writes or deletes.
RedisKvStore uses bounded scripts and a restricted engine list because Redis scripts do not undo earlier writes when a later command fails. Its complete input encoding, execution-time key reads, command-permission checks, and script bounds are part of the all-or-nothing argument. An isolated EVAL or a MULTI/EXEC sequence alone does not establish this contract. Keep those Redis constraints when extending its implementation.
Implement ~AtomicKvStore.casMany() method
Protect the complete read set against competing clients, including absent and expired keys. Compare all expected values against the same pre-mutation state, then apply all replacements and deletions together. Do not batch independent cas() calls or recheck expectations after earlier writes have changed the state. A conditional statement affecting zero rows need not be a backend error, so a transaction alone does not ensure every condition succeeded.
Use backend concurrency controls with a documented isolation level and key scope. A process-local mutex cannot coordinate other handles or processes. On a deadlock retry, roll back and re-evaluate the complete expected set. Return false only for a comparison mismatch; propagate backend errors.
For example, PgliteKvStore uses the exclusive transaction callback of one supported PGlite owner. Independent store wrappers share that owner, whose client queue excludes other normal queries for the callback's entire lifetime, including checks for absent keys.
For PostgreSQL adapters, locking only existing rows does not protect absent keys. PostgresKvStore uses a table write lock followed by a fresh READ COMMITTED snapshot; its client restrictions also require exclusive sequential use of caller-owned transactions. PostgreSQL locks and nested savepoints do not isolate overlapping calls in the same outer transaction. Test supported independent clients rather than assuming one transaction-scoped handle provides that concurrency.
Run the shared atomic conformance tests, using independent clients sharing an isolated backend for persistent adapters. Add backend-specific competing-client, rollback, expiry, and injected-failure tests; shared tests cannot establish crash durability or cover every backend failure mode.
Use your custom KvStore
That's it! You can now use your custom KvStore implementation with Fedify:
import { createFederation } from "@fedify/fedify";
const customKvStore = new MyCustomKvStore();
const federation = createFederation<void>({
kv: customKvStore,
// ... other options
});