LIVE • TECH, ENTERPRISE ERP & RETAIL AI JOURNAL
Bijak Technology
🌐id
⚖️Independent Research • Verified Affiliate Transparency

Offline-First POS Architecture with NATS & Automerge

Implement NATS JetStream Leaf Nodes and Automerge CRDTs for reliable offline-first retail data synchronization between edge gateways and cloud.

Offline-First POS Architecture with NATS & Automerge
Author: (Principal Software Architect) •Reviewed by: Bijak Technology Editorial Board •Published:

Distributed retail systems operating across hundreds of physical locations face frequent network degradation. Standard point-of-sale (POS) architectures that depend on constant WAN availability suffer from transaction blocking, latency spikes, and complete store operational stalls when cellular or landline internet drops. Building an offline-first architecture addresses this instability by moving data persistence and business execution to edge gateways inside the retail store, deferring state synchronization until connectivity resumes.

This architectural analysis details how to implement an offline-first edge-to-cloud data stream using NATS JetStream Leaf Nodes combined with Automerge Conflict-Free Replicated Data Types (CRDTs).

Local mutations commit directly to edge storage without blocking checkout threads.

Edge Gateway Topologies and Local Persistence with NATS Leaf Nodes

Traditional retail IT infrastructures route every POS mutation directly to a centralized cloud database. Under unstable network conditions, HTTP timeouts and TCP connection retries stall the checkout line. An offline-first design decouples the POS terminal from the cloud network entirely. The POS application communicates exclusively with a local edge gateway deployed on low-power hardware, such as an ARM64 single-board computer or industrial Mini-PC located on the store’s local area network (LAN).

+-------------------------------------------------------------------+
| STORE LOCATION EDGE                                               |
|                                                                   |
|   +------------------+     +----------------------------------+   |
|   | Local POS Client |---->| Edge Gateway (ARM64)             |   |
|   | (Automerge App)  |     | - NATS JetStream Leaf Node       |   |
|   +------------------+     | - Disk Persistence (/data/nats)  |   |
|                            +-----------------|----------------+   |
+----------------------------------------------|--------------------+
                                               |
                                  WAN Link     | (Intermittent LTE /
                                  Degraded     |  Fiber Connection)
                                               v
+-------------------------------------------------------------------+
| CLOUD HUB                                                         |
|                                                                   |
|   +-----------------------------------------------------------+   |
|   | Central NATS Server (JetStream Cluster)                   |   |
|   | - Port 7422 (Leafnode Receiver)                           |   |
|   | - Stream Aggregation & Automerge State Convergence        |   |
|   +-----------------------------------------------------------+   |
+-------------------------------------------------------------------+

NATS JetStream provides message persistence and stream processing capabilities at the edge. To bridge local operations with central cloud infrastructure, NATS supports leaf nodes. A leaf node is a lightweight NATS server running locally that acts as a standalone broker for in-store clients while establishing an upstream connection to a central NATS JetStream hub.

When the WAN connection fails, the leaf node continues serving local POS pub/sub requests, buffering published messages directly to local NVMe or eMMC storage. Once the network link recovers, the leaf node re-establishes its TLS session with the remote cluster using built-in reconnect backoff and streams accumulated local JetStream messages to the cloud.

The following configuration defines a central NATS JetStream hub enabled to accept leaf node connections:

# /etc/nats/nats-hub.conf (Cloud Hub Configuration)
server_name: "cloud-hub"
port: 4222

leafnodes {
  port: 7422
}

jetstream {
  store_dir: "/var/nats/jetstream"
  max_memory_store: 4GB
  max_file_store: 100GB
}

On the store’s local ARM64 gateway, the NATS leaf node connects to the cloud hub while maintaining bounded local disk persistence:

# /etc/nats/nats-leaf.conf (Store Edge Gateway Configuration)
server_name: "store-042-leaf"
port: 4222

leafnodes {
  remotes: [
    {
      url: "nats://cloud-hub.internal.example.com:7422"
      credentials: "/etc/nats/certs/leaf-store-042.creds"
    }
  ]
}

jetstream {
  store_dir: "/data/nats/jetstream"
  max_memory_store: 512MB
  max_file_store: 10GB
}

Because the POS client connects strictly to nats://127.0.0.1:4222 on the edge gateway, network drops on the WAN interface remain transparent to cashiers. Message publishing succeeds locally regardless of backhaul availability.

Conflict-Free State Convergence Using Automerge Counters

Local persistence solves message queuing during network outages, but it does not address data reconciliation. If two POS terminals in different stores—or two isolated registers within the same store—modify inventory states independently while offline, standard database writes collide. Relying on centralized primary keys, Two-Phase Commit (2PC), or strict transactional locks requires low-latency, uninterrupted WAN availability, making them unsuitable for offline-first deployments.

State-based CRDTs enable deterministic state convergence across distributed nodes without lock coordination. Automerge tracks change histories as directed acyclic graphs (DAGs) of operations, encoding causal metadata inside each binary change payload rather than relying on unreliable wall-clock timestamps.

One critical implementation detail separates working production code from silent inventory corruption: using plain JavaScript numbers versus Automerge.Counter. If Store A starts with 10 units and mutates a plain number (count -= 1 to 9) while Store B concurrently mutates the same baseline (count -= 2 to 8), Automerge treats scalar number assignments as a Last-Writer-Wins (LWW) register conflict—reconciling arbitrarily to 9 or 8 instead of 7. Using Automerge.Counter records relative deltas (decrement(1) and decrement(2)) so both operations commute cleanly to 7.

  [ Store A Offline ] ---> Counter.decrement(1) ---\
                                                    +--> Automerge.applyChanges() --> Stock = 7
  [ Store B Offline ] ---> Counter.decrement(2) ---/   (Commutative Convergence)

Initialize the SKU inventory with Automerge.Counter before exporting the baseline state:

import * as Automerge from '@automerge/automerge';

// Initialize baseline inventory with a commutative CRDT Counter
let baseDoc = Automerge.change(Automerge.init(), 'Initialize SKU Stock', doc => {
  doc.inventory = {
    'SKU-8821': { count: new Automerge.Counter(10), reserved: new Automerge.Counter(0) }
  };
});

const baselineBytes = Automerge.save(baseDoc);

When an offline POS register completes a checkout, decrement the counter and publish the resulting Uint8Array change frames into the local JetStream subject:

// Local mutation during offline store operation
const currentDoc = Automerge.load(baselineBytes);

const nextDoc = Automerge.change(currentDoc, 'POS checkout decrement', doc => {
  doc.inventory['SKU-8821'].count.decrement(1);
});

// Extract incremental binary changes (Uint8Array[]) since baseline
const changes = Automerge.getChanges(currentDoc, nextDoc);
for (const changeBytes of changes) {
  await nc.publish('store.042.inventory.mutations', changeBytes);
}

When the leaf node re-establishes connectivity with the central NATS JetStream server, accumulated binary frames stream into the cloud hub. A cloud consumer reads the stream and applies Automerge.applyChanges(cloudDoc, receivedChanges) to the master document. Regardless of message arrival order, the counter converges deterministically across all replicas.

However, CRDTs incur causal history overhead. Automerge stores historical operations in its DAG to guarantee deterministic merges. Without periodic history compaction and snapshotting, binary document sizes grow continuously and consume excessive RAM on constrained ARM64 gateways.

Provisioning the Hub Stream and Validating WAN Isolation

Deploying this architecture requires provisioning the local JetStream store, wiring the POS runtime to the local broker, and testing network partition recovery before rollout.

Creating the Local Inventory Mutation Stream

Provision the central NATS cluster with JetStream enabled and port 7422 exposed behind TLS/mTLS authentication. On each store’s ARM64 edge gateway, initialize a file-backed JetStream stream to capture mutations durably across reboots:

nats stream add INVENTORY_MUTATIONS \
  --subjects="store.*.inventory.mutations" \
  --storage=file \
  --retention=limits \
  --max-bytes=8GB \
  --discard=old

Wiring POS Runtime Storage and Edge Drivers

Configure the POS runtime software to load its Automerge document from local disk on startup, apply counter decrements on each completed sale, persist the updated document snapshot locally, and publish encoded changes to nats://127.0.0.1:4222. For hardware peripheral and CGNAT tunnel patterns on Linux store gateways, refer to our guide on POS edge driver architectures.

Verifying Partition Tolerance and State Convergence

Simulate a physical link outage on a staging gateway by taking down the primary WAN interface:

sudo ip link set dev eth0 down

Process concurrent transactions on two isolated POS instances starting from baseline stock 10: Store A calls .decrement(1) while Store B calls .decrement(2). Verify both checkouts succeed locally with zero UI stalls or connection timeouts, then restore WAN connectivity:

sudo ip link set dev eth0 up

Observe the NATS leaf node logs as it renegotiates TLS with the cloud hub and flushes INVENTORY_MUTATIONS. Once the cloud materializer executes Automerge.applyChanges(), inspect cloudDoc.inventory['SKU-8821'].count.value to confirm deterministic convergence to 7.

System Architecture Trade-Offs and Edge Constraints

While an offline-first NATS JetStream and Automerge design preserves store availability during outages, it introduces concrete architectural trade-offs that engineering teams must govern explicitly.

System Property Synchronous 2PC Hub Offline-First (NATS JetStream + Automerge)
WAN Dependency Strict (outages block checkouts) Independent (local disk commits continue)
State Convergence Immediate linearizability Eventual deterministic convergence
Physical Overselling Prevented by central DB locks Unpreventable during active partitions
Edge Storage Footprint Minimal (stateless terminal) High (JetStream WAL + CRDT DAG history)
Ordering Mechanism Central transaction serialization Logical causal DAG (not wall-clock NTP)
  • WAN Dependency — Synchronous 2PC Hub: Strict (outages block checkouts) | Offline-First (NATS JetStream + Automerge): Independent (local disk commits continue)
  • State Convergence — Synchronous 2PC Hub: Immediate linearizability | Offline-First (NATS JetStream + Automerge): Eventual deterministic convergence
  • Physical Overselling — Synchronous 2PC Hub: Prevented by central DB locks | Offline-First (NATS JetStream + Automerge): Unpreventable during active partitions
  • Edge Storage Footprint — Synchronous 2PC Hub: Minimal (stateless terminal) | Offline-First (NATS JetStream + Automerge): High (JetStream WAL + CRDT DAG history)
  • Ordering Mechanism — Synchronous 2PC Hub: Central transaction serialization | Offline-First (NATS JetStream + Automerge): Logical causal DAG (not wall-clock NTP)

Physical Inventory Overselling Under Partition

Automerge guarantees mathematical convergence of digital state, not physical inventory availability. If Store A and Store B each hold the final 1 physical unit of an SKU in shared visibility and sell it simultaneously while partitioned offline, the merged state accurately converges to -1. Operational workflows must include post-reconciliation handling such as back-ordering, warehouse reallocation, or automated stock alerts.

Incompatibility with Strict ACID Financial Ledgers

This pattern cannot replace an enterprise relational database requiring strict linearizability or real-time ACID isolation. General ledger double-entry postings, sequential tax invoice numbering, and credit limit enforcement still demand centralized coordination or strong global consistency.

Physical Storage Limits and Compaction Discipline

Local buffering durability depends directly on the edge gateway’s NVMe or eMMC capacity. Keep JetStream max_file_store capped below 70% of usable disk space so extended outages trigger bounded log retention instead of starving the operating system, and schedule daily Automerge snapshot compaction after store close to prune unbounded DAG growth.

Logical Causality vs. Audit Timestamps

Automerge bypasses clock skew corruption during state merges by relying on logical causality rather than wall-clock timestamps. However, financial and operational audit trails still require deploying chrony or systemd-timesyncd across edge nodes so recorded transaction timestamps remain aligned within acceptable tolerances.

About the Author: Iswan Putera is Principal Software Architect and Lead Technology Writer at Bijak Technology with over a decade of hands-on experience in distributed systems, Linux cloud infrastructure, and enterprise ERPNext implementations. Connect directly via LinkedIn, commercial portfolio Samkarsa, or email redaksi@bijaktechnology.com.

Related Tags:#NATS JetStream#Edge Computing#CRDT#Automerge#RetailTech#Distributed Systems
IP

Iswan Putera

Principal Software Architect

Software Architect & Senior Systems Engineer with over a decade of hands-on expertise in distributed architectures, Linux private cloud deployments, and enterprise ERP implementations. Serves as Lead Technology Writer at Bijak Technology.

Share