How to sync local document state from serverless and edge runtimes to a MongoDB backend

When an agent workflow is interrupted by isolate eviction, relying on a central database for every intermediate step often results in partial writes, inconsistent state, and high latency. To build resilient, multi-step agent workflows on edge runtimes, you must decouple the agent's hot working state from the durable system of record. By using MongoLite (npm: @semics-tech/mongolite) to manage local progress against a SQLite backend, you can perform atomic local commits, then reconcile that state with your central MongoDB deployment using an outbox pattern and idempotent operations.

Why do edge agents need local document state?

Edge runtimes like Cloudflare Workers or serverless functions are ephemeral. If an agent performs a network round trip to a central MongoDB instance for every state update, you introduce latency and increase the surface area for partial failures. If the runtime environment terminates mid-execution, a system relying on synchronous remote writes often loses the intermediate state of the operation. Maintaining a local document store with MongoLite allows the agent to commit progress locally against a SQLite backend, providing a reliable buffer against network instability and runtime evictions.

What is the recommended architecture for state synchronisation?

The architecture relies on a clear separation between the agent's execution environment and the persistent system of record. The data flow follows this pattern:

  1. The agent isolate interacts with local collections via MongoLite to update state and append to an outbox collection within the same logical unit of work.
  2. A background sync worker or scheduled task reads the outbox.
  3. The sync worker pushes updates to the central MongoDB deployment using idempotent operations.

How do you manage persistence across different runtime adapters?

Different runtimes impose specific limits on storage durability. You must declare your persistence requirements per adapter rather than assuming global durability. The following table outlines the trade-offs for common backends supported by the semics-tech/mongolite repository.

Adapter Durability Concurrency Best Use Case
In-memory SQLite Ephemeral (lost on eviction) Single-isolate Short-lived, single-step tasks
SQLite File Persistent (if volume mounted) Limited Local development or persistent sidecars
Cloudflare Durable Objects Persistent Strongly consistent Multi-step agent state
Browser (sql.js) In memory; persist it via OPFS or by exporting the database to IndexedDB Client-side Offline-first browser agents

How do you handle cold starts and index bootstrap?

In serverless environments, cold starts can be costly. Schema and index bootstrap must be lazy and cheap. Avoid blocking the main execution path with heavy database initialisation. Use a guarded lazy initialisation pattern to ensure your collection and indexes are ready only when needed.


let dbInstance;
async function getDb() {
  if (!dbInstance) {
    dbInstance = await initSqlite();
    // Lazy index creation
    await dbInstance.collection('agent_state').createIndex({ runId: 1 });
  }
  return dbInstance;
}

How do you implement atomic write synchronisation?

To achieve atomic synchronisation, use an outbox pattern combined with idempotency keys. When the agent completes a step, it updates the working document and inserts an event into the outbox. The sync worker then reads from the outbox and attempts an upsert on the central MongoDB instance using the idempotency key to prevent duplicate processing.


// Committing an agent step locally
await db.collection('agent_state').findOneAndUpdate(
  { _id: 'run_123' },
  { 
    $push: { steps: { stepId: 5, status: 'completed' } },
    $currentDate: { lastUpdated: { $type: 'timestamp' } }
  }
);

// Appending to the outbox with an idempotency key
await db.collection('outbox').insertOne({
  _id: 'step_5_idempotency_key',
  op: 'update',
  target: 'agent_state',
  payload: { stepId: 5 },
  seq: 5
});

On the MongoDB side, use the $setOnInsert operator to ensure that retries do not overwrite existing data or create duplicate entries:


// MongoDB-side idempotent upsert
await mongoClient.db('prod').collection('agent_state').findOneAndUpdate(
  { _id: 'run_123' },
  { 
    $push: { steps: { stepId: 5, status: 'completed' } },
    $setOnInsert: { createdAt: new Date() }
  },
  { upsert: true }
);

What are the available conflict resolution strategies?

Conflict resolution is an explicit architectural choice. You must decide how to handle concurrent updates before implementing your sync logic:

  • Last-Write-Wins (LWW): Attach a version field or timestamp to your documents. The sync worker only updates if the incoming version is greater than the current version in MongoDB.
  • Per-field merge: Use specific update operators to merge changes without overwriting the entire document.
  • Accumulate-only: Use operators like $addToSet or $push to ensure that no data is ever lost, only appended.

What does this pattern not give you?

This pattern does not provide distributed ACID transactions across SQLite and MongoDB. You are effectively managing eventual consistency. While MongoLite provides MongoDB parity for many operations, complex aggregation pipelines that cannot be pushed down to SQLite will be evaluated in memory. Be mindful of memory limits in constrained environments; if your pipeline processes large datasets, you risk isolate termination. Always verify your specific query patterns against the parity test suite in the semics-tech/mongolite repository to ensure consistent behaviour.

We invite you to implement this pattern by installing @semics-tech/mongolite and running these snippets against a local SQLite file first, then transitioning to a Durable Object. If you encounter a specific edge case or an aggregation stage that behaves unexpectedly, please open an issue on GitHub to help improve the parity suite for everyone.