Skip to content

POS & Edge Sync (m_pos)

The m_pos library is Business M’s offline-capable Point-of-Sale (POS) engine. It enables retail counters, kiosks, and canteen outlets to process sales transactions at high throughput with zero latency. It supports both fully connected central environments and intermittently connected or air-gapped retail counters with automatic reconciliation.


The system operates in one of two distinct deployment modes, configured per PosProfile via the deployment_mode field:

Feature / Behavior Mode 1: Central Cloud Mode Mode 2: Federated Edge Mode
Profile Setting deployment_mode = "central" deployment_mode = "edge" (requires region and zone)
Topology Cloud to PWA: Kiosk/Browser connects directly to Cloud API Cloud to Edge to PWA: Kiosk/Browser connects to local Edge server; Edge synchronizes with Cloud
Target Scale Small retail stores, corporate canteens, high-bandwidth outlets Large retail networks (4000+ outlets/URCs), remote depots, low-bandwidth sites
Local Database Browser IndexedDB (Dexie) for temporary network drops Local PostgreSQL/SQLite on Edge node + Browser IndexedDB on Kiosks
Quota Allocation Real-time (per_invoice or per_session) with Cloud DB lock Session pre-allocation (per_session) without cloud locks during billing
Downstream Ledger Instant outbox event dispatched to Finance & WMS Local invoice committed first; pushed to Cloud asynchronously via JetStream / RPC batch
Conflict Resolution Real-time validation against cloud master records Asynchronous 3-tier resolution (Auto-Policy → Drift Tolerance → Manual Reconciliation)

In Central Cloud Mode, POS counters and kiosks connect directly over HTTPS to the central Business M cloud cluster.

graph TD
    subgraph Counter / Kiosk
        PWA["POS PWA (React / Vite)"]
        Dexie["IndexedDB (offlineQueue.ts)"]
    end

    subgraph Central Cloud Cluster
        CloudAPI["m_pos API (Litestar / RPC)"]
        CloudDB[("Cloud PostgreSQL")]
        Outbox["_outbox Table"]
        NATS["NATS JetStream"]
        FinanceWorker["Finance Worker (pos_sync_worker)"]
        WmsWorker["WMS Worker (pos_sync_worker)"]
        FinanceLedger[("SalesInvoice & PaymentReceipt")]
        WmsLedger[("StockEntry")]
    end

    PWA -->|"RPC: create_pos_invoice"| CloudAPI
    PWA -.->|"Network Interrupted"| Dexie
    Dexie -.->|"Background Sync / Online"| CloudAPI
    CloudAPI -->|"Direct Write (synced_to_cloud=True)"| CloudDB
    CloudAPI -->|"Enqueue Job"| Outbox
    Outbox -->|"Outbox Worker"| NATS
    NATS -->|"m_pos.sale.completed.v1"| FinanceWorker
    NATS -->|"m_pos.sale.completed.v1"| WmsWorker
    FinanceWorker --> FinanceLedger
    WmsWorker --> WmsLedger
  1. Session Opening: Cashier opens a session via open_session(pos_profile_id, opening_cash). The session record is created directly in the central Cloud database with deployment_mode = "central".
  2. Transaction Processing:
    • Kiosk calls create_pos_invoice(session_id, payload).
    • Cloud validates the cashier’s session, customer, stock availability, and smart card quota directly against the live database.
    • PosInvoice is inserted with synced_to_cloud = True.
  3. Downstream Accounting & Inventory:
    • Upon successful database commit, the system enqueues m_pos.publish_sale_completed_event.
    • The job writes an OutboxEntry with target m_pos.sale.completed.v1.
    • The framework’s outbox_worker relays the event over NATS JetStream.
    • finance.services.pos_sync_worker subscribes to the event and creates/submits the official SalesInvoice and PaymentReceipt.
    • wms.services.pos_sync_worker subscribes and creates/submits the corresponding StockEntry (Issue) to deduct inventory.
  4. PWA Disconnect Failover:
    • If the counter’s internet connection drops temporarily, offlineQueue.ts captures the transaction payload in browser IndexedDB (Dexie).
    • Once connectivity is restored, the Service Worker Background Sync automatically flushes queued invoices to create_pos_invoice.

Mode 2: Federated Edge Mode (Cloud to Edge to PWA)

Section titled “Mode 2: Federated Edge Mode (Cloud to Edge to PWA)”

In Federated Edge Mode, each physical retail store runs a lightweight local edge server (m_pos API and worker with local Postgres/SQLite). The counter PWAs communicate locally with the store’s edge server over the local area network (LAN), ensuring zero latency and 100% billing continuity even during prolonged internet outages.

graph TD
    subgraph Retail Counter / Kiosk
        PWA["POS PWA (React)"]
    end

    subgraph Store Edge Server
        EdgeAPI["Edge m_pos API"]
        EdgeDB[("Local PostgreSQL / SQLite")]
        EdgeWorker["Edge Background Worker"]
    end

    subgraph Central Cloud
        CloudAPI["Cloud Ingress API\n(/pos/master_data, /pos/sync_outbox)"]
        CloudQueue["NATS JetStream Worker Pool"]
        SyncService["JetStreamSyncService (LWW)"]
        CloudDB[("Central PostgreSQL")]
        ReconUI["Reconciliation Dashboard"]
        Ledgers["Finance & WMS Ledgers"]
    end

    PWA <-->|"LAN RPC (0ms Internet Dependency)"| EdgeAPI
    EdgeAPI -->|"Commit (synced_to_cloud=False)"| EdgeDB
    EdgeDB --> EdgeWorker
    EdgeWorker -.->|"Pull Master Data"| CloudAPI
    EdgeWorker -.->|"Push Batch Sync"| CloudAPI
    CloudAPI --> CloudQueue
    CloudQueue --> SyncService
    SyncService -->|"Fresh (Insert/Update)"| CloudDB
    SyncService -.->|"Conflict (LWW_REJECTED)"| ReconUI
    CloudDB --> Ledgers

1. Master Data Synchronization (Pre-shift)

Section titled “1. Master Data Synchronization (Pre-shift)”

Before going offline, the edge server pulls the latest catalog and customer data from the Cloud using GET /api/v1/rpc/fn/m_pos.api.offline_billing.get_master_data:

  • Live selling prices (WmsItem mrp, business_price, domain_price)
  • Active customer list and account states

2. Session Opening & Smart-Card Quota Pre-Allocation

Section titled “2. Session Opening & Smart-Card Quota Pre-Allocation”

To avoid distributed locks and latency during peak billing:

  • When an edge session opens, the operator can request a quota block for smart-card beneficiaries via allocate_card_quota().
  • Quota is reserved atomically on the central card and allocated to the local PosSession.
  • During billing, the edge server decrements the card balance locally from the session allocation without roundtripping to the cloud.
  • When close_session() is executed, all unused quota is automatically returned to the central beneficiary card.
  • Cashier generates invoices via create_pos_invoice().
  • Invoices are committed to the local edge database with synced_to_cloud = False.
  • The counter can process thousands of transactions with zero cloud dependency.

4. Cloud Ingestion & Last-Write-Wins (LWW) Resolution

Section titled “4. Cloud Ingestion & Last-Write-Wins (LWW) Resolution”

When internet connectivity is restored:

  • The edge node transmits accumulated outbox invoices via POST /api/v1/rpc/fn/m_pos.api.offline_billing.push_sync_payloads.
  • Central cloud workers process each payload asynchronously through JetStreamSyncService.process_sync_payload().
  • Last-Write-Wins (LWW): Timestamps (modified) on incoming edge payloads are compared against cloud records:
    • Fresh Payloads (edge_modified > cloud_modified): Document is inserted or updated in Cloud DB. m_pos.publish_sale_completed_event is enqueued, propagating to Finance and WMS ledgers.
    • Stale Payloads (cloud_modified >= edge_modified): Evaluated against configured PosConflictPolicy rules. If not auto-resolvable, a PosSyncConflict record is created.

In Mode 2, when edge payloads arrive out-of-order or conflict with central constraints, the system resolves them via a 3-tier hierarchy:

graph TD
    A["Incoming Edge Payload"] --> LWW{"Cloud Modified >= Edge Modified?"}
    LWW -->|"No (Fresh)"| Accept["Accept: Insert/Update Cloud Document"]
    LWW -->|"Yes (Conflict)"| T1{"Tier 1: PosConflictPolicy"}
    
    T1 -->|"Auto-resolve Rule Matches"| Action["Apply Policy: 'override' or 'keep_cloud'"]
    T1 -->|"No Policy Match"| T2{"Tier 2: Business Tolerance"}
    
    T2 -->|"Price Drift <= Tolerance %"| Drift["Accept & Flag Drift Journal"]
    T2 -->|"Stock Deficit Allowed"| Stock["Accept & Flag Negative Stock"]
    T2 -->|"Exceeds Tolerances"| T3["Tier 3: Manual Review"]
    
    T3 --> ConflictDoc["Create PosSyncConflict (Status: Pending)"]
    ConflictDoc --> Dashboard["Reconciliation Dashboard (/wms/pos-reconciliation)"]

Configurable Conflict Policies (PosConflictPolicy)

Section titled “Configurable Conflict Policies (PosConflictPolicy)”

Administrators can configure automated resolution rules per PosProfile for known conflict types:

  • LWW_REJECTED: Timestamp collision.
  • PRICE_DRIFT: Price changed on cloud while offline.
  • CUSTOMER_INACTIVE: Customer deactivated on cloud while offline.
  • ITEM_UNLISTED: Item removed from catalog while offline.
  • QUOTA_EXCEEDED: Optimistic quota limit breached.

Both modes benefit from client-side browser resiliency implemented in libs/m_pos/frontend/src/services/offlineQueue.ts:

  1. Storage: Invoices are stored in IndexedDB using Dexie (PosOfflineDatabase).
  2. Background Sync: Registered with navigator.serviceWorker.ready under tag pos-invoice-sync.
  3. Retry Strategy: Up to 5 retries with exponential backoff.
  4. Validation Handling: HTTP 4xx validation errors are dropped from the queue with an error log to prevent poison-pill retries; 5xx errors and network drops are retried automatically.

To deploy an Edge Server node at a retail counter or canteen outlet, run the following docker-compose.m_pos_edge.yml:

version: '3.8'
services:
db:
image: postgres:15-alpine
environment:
POSTGRES_USER: admin
POSTGRES_PASSWORD: changeme
POSTGRES_DB: business_m_edge
volumes:
- edge_pgdata:/var/lib/postgresql/data
redis:
image: valkey/valkey:7.2.5-alpine
m_pos_api:
image: registry.gitlab.com/castlecraft/business-m/m_pos:latest
ports:
- "8000:8000"
environment:
- DATABASE_URL=postgresql+asyncpg://admin:changeme@db:5432/business_m_edge
- REDIS_URL=redis://redis:6379/0
- NATS_URL=nats://<cloud-nats-server>:4222
- FRAMEWORK_MODE=MACROSERVICE
- FRAMEWORK_M_SERVICE_NAME=m_pos
- INSTALLED_APPS=m_pos
- ZONE=north
- REGION=delhi_ncr
- DEPLOYMENT_MODE=edge
depends_on:
- db
- redis
m_pos_worker:
image: registry.gitlab.com/castlecraft/business-m/m_pos:latest
command: ["uv", "run", "m", "worker"]
environment:
- DATABASE_URL=postgresql+asyncpg://admin:changeme@db:5432/business_m_edge
- REDIS_URL=redis://redis:6379/0
- NATS_URL=nats://<cloud-nats-server>:4222
- FRAMEWORK_MODE=MACROSERVICE
- FRAMEWORK_M_SERVICE_NAME=m_pos
- INSTALLED_APPS=m_pos
- ZONE=north
- REGION=delhi_ncr
- DEPLOYMENT_MODE=edge
depends_on:
- db
- redis
volumes:
edge_pgdata: