Building a resilient offline-first retail POS system with Python, SQLite, idempotent APIs, and reliable transaction synchronization.
Introduction
It's a busy Saturday afternoon. A retail store is processing dozens of transactions when its internet connection suddenly goes down.
Customers are waiting, store associates need to complete purchases, and the central ERP system is temporarily unreachable.
Should the POS terminal stop processing transactions until connectivity returns?
For many retail businesses, that isn't a practical option.
An offline-capable Point of Sale (POS) system needs to continue recording supported sales, preserve transaction data locally, and synchronize those transactions with central retail systems when connectivity is restored.
But offline processing introduces several technical challenges:
- How do we prevent transactions from being lost?
- What happens when synchronization fails halfway through?
- How do we avoid duplicate sales during retries?
- What happens when multiple stores sell the same product while offline?
- How should conflicting inventory records be handled?
In this tutorial, we'll explore how developers can address these challenges using Python, SQLite, persistent synchronization queues, retry strategies, and idempotent APIs.
1. Understanding Offline-First POS Architecture
An offline-first application is designed to remain functional when network connectivity is unavailable.
Instead of requiring every operation to communicate immediately with a remote server, the application records supported operations locally and synchronizes them later.
A simplified offline POS architecture looks like this:
POS Terminal | v Local Transaction Database | v Persistent Sync Queue | v Background Sync Worker | v Central Retail API | v ERP / Inventory Database When the network is available, transactions can be synchronized almost immediately.
When connectivity is interrupted, transactions remain safely stored in the local database.
Once connectivity returns, the synchronization worker processes the pending records.
The important architectural principle is that recording a sale and transmitting it to the central server are separate operations.
2. Creating a Persistent Local Transaction Database
Let's build a simplified offline transaction system using Python and SQLite.
SQLite is suitable for this demonstration because it provides persistent local storage without requiring a separate database server.
Install the HTTP client library:
pip install requests Create a file named database.py.
import sqlite3 DB_PATH = "offline_pos.db" def get_connection(): conn = sqlite3.connect(DB_PATH, timeout=10) conn.row_factory = sqlite3.Row return conn def initialize_database(): with get_connection() as conn: conn.executescript(""" CREATE TABLE IF NOT EXISTS transactions ( transaction_id TEXT PRIMARY KEY, store_id TEXT NOT NULL, product_id TEXT NOT NULL, quantity INTEGER NOT NULL, total_cents INTEGER NOT NULL, created_at TEXT NOT NULL ); CREATE TABLE IF NOT EXISTS sync_queue ( transaction_id TEXT PRIMARY KEY, payload TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, next_retry_at REAL NOT NULL DEFAULT 0, last_error TEXT, FOREIGN KEY (transaction_id) REFERENCES transactions(transaction_id) ); """) if __name__ == "__main__": initialize_database() Run the script:
python database.py The database contains two tables.
The transactions table stores completed local sales, while the sync_queue table tracks transactions waiting to be transmitted.
Separating these responsibilities makes it easier to manage synchronization without modifying the original sales records.
Notice that monetary values are stored as integer cents rather than floating-point numbers. This avoids common rounding problems when handling financial data.
3. Recording Sales and Queue Entries Atomically
One of the most important requirements in offline POS architecture is ensuring that every recorded sale has a corresponding synchronization record.
Consider what happens if the POS application records a sale but crashes before adding it to the synchronization queue.
The transaction exists locally, but the central system may never receive it.
We can prevent this by inserting both records within the same database transaction.
Create a file named pos.py.
import json import uuid from datetime import datetime, timezone from database import get_connection def record_sale(store_id, product_id, quantity, total_cents): if quantity <= 0 or total_cents < 0: raise ValueError("Invalid sale") transaction_id = str(uuid.uuid4()) payload = { "transaction_id": transaction_id, "store_id": store_id, "product_id": product_id, "quantity": quantity, "total_cents": total_cents, "created_at": datetime.now( timezone.utc ).isoformat() } with get_connection() as conn: conn.execute(""" INSERT INTO transactions ( transaction_id, store_id, product_id, quantity, total_cents, created_at ) VALUES (?, ?, ?, ?, ?, ?) """, ( transaction_id, store_id, product_id, quantity, total_cents, payload["created_at"] )) conn.execute(""" INSERT INTO sync_queue ( transaction_id, payload ) VALUES (?, ?) """, ( transaction_id, json.dumps(payload) )) return transaction_id if __name__ == "__main__": transaction_id = record_sale( "STORE-001", "SKU-1001", 2, 9998 ) print("Sale recorded:", transaction_id) Run:
python pos.py The sale is now recorded locally, even without an internet connection.
Because both inserts occur within the same SQLite transaction, either both records are committed or neither is.
This is a simplified implementation of the transactional outbox pattern, which is widely used in distributed systems to improve the reliability of event delivery.
4. Building the Synchronization Worker
The synchronization worker retrieves pending transactions and sends them to the central retail API.
A production application might run this worker as a background service, scheduled process, or dedicated synchronization component.
For this example, we'll use a simple Python worker.
Create a file named sync_worker.py.
import json import random import time import requests from database import get_connection API_URL = "http://127.0.0.1:8000/sales" MAX_ATTEMPTS = 10 def update_status(transaction_id, status, error=None): with get_connection() as conn: conn.execute(""" UPDATE sync_queue SET status = ?, last_error = ? WHERE transaction_id = ? """, (status, error, transaction_id)) def schedule_retry(transaction_id, attempts, error, minimum_delay=0): attempts += 1 if attempts >= MAX_ATTEMPTS: status = "review_required" next_retry = 0 else: status = "pending" delay = min(300, 2 ** attempts) delay += random.uniform(0, 1) next_retry = time.time() + max( delay, minimum_delay ) with get_connection() as conn: conn.execute(""" UPDATE sync_queue SET attempts = ?, next_retry_at = ?, status = ?, last_error = ? WHERE transaction_id = ? """, ( attempts, next_retry, status, error, transaction_id )) def sync_transactions(): with get_connection() as conn: rows = conn.execute(""" SELECT * FROM sync_queue WHERE status = 'pending' AND next_retry_at <= ? ORDER BY rowid LIMIT 50 """, (time.time(),)).fetchall() for row in rows: transaction_id = row["transaction_id"] payload = json.loads(row["payload"]) try: response = requests.post( API_URL, json=payload, headers={ "Idempotency-Key": transaction_id }, timeout=10, allow_redirects=False ) if response.status_code in (200, 201): update_status( transaction_id, "synced" ) elif response.status_code == 409: update_status( transaction_id, "conflict", response.text[:500] ) elif response.status_code in (408, 429) \ or response.status_code >= 500: retry_after = response.headers.get( "Retry-After", "" ) minimum_delay = ( int(retry_after) if retry_after.isdigit() else 0 ) schedule_retry( transaction_id, row["attempts"], f"HTTP {response.status_code}", minimum_delay ) else: update_status( transaction_id, "review_required", f"HTTP {response.status_code}" ) except requests.RequestException as exc: schedule_retry( transaction_id, row["attempts"], type(exc).__name__ ) if __name__ == "__main__": while True: sync_transactions() time.sleep(5) This worker performs several important operations:
- Retrieves eligible pending transactions.
- Sends transaction data to the central API.
- Includes an idempotency key.
- Marks successful transactions as synchronized.
- Schedules retries for temporary failures.
- Separates conflicts from ordinary network errors.
- Preserves unresolved transactions for review.
This example assumes a single synchronization worker per local database. Multiple concurrent workers would require an atomic queue-claiming mechanism or processing leases.
5. Implementing Exponential Backoff and Retry Strategies
Network failures are often temporary.
A POS terminal might lose connectivity because of Wi-Fi interruptions, API timeouts, server maintenance, or network congestion.
Immediately retrying every failed request can make the situation worse, particularly when hundreds of POS terminals attempt to reconnect simultaneously.
Exponential backoff gradually increases the delay between retry attempts.
A typical retry sequence might look like this:
Attempt 1 → Retry after 2 seconds Attempt 2 → Retry after 4 seconds Attempt 3 → Retry after 8 seconds Attempt 4 → Retry after 16 seconds Attempt 5 → Retry after 32 seconds Adding random jitter helps prevent multiple terminals from retrying at exactly the same time.
However, not every failure should be retried.
Network timeouts, temporary server errors, and rate limits are generally suitable for automatic retries.
Invalid transaction data, authorization failures, and business-rule conflicts require different handling.
For long offline periods, production systems should also distinguish connectivity outages from repeated transaction-specific failures. A store should not have to manually review every valid transaction simply because its internet connection was unavailable for several hours.
6. Preventing Duplicate Transactions with Idempotent APIs
Consider this scenario:
- A POS terminal sends a sale to the central server.
- The server successfully records the transaction.
- The network disconnects before the terminal receives confirmation.
- The terminal retries the same transaction.
Without idempotency, the central system might record the same sale twice.
This could result in incorrect inventory quantities, duplicated revenue, inaccurate financial reports, and reconciliation problems.
An idempotent API ensures that processing the same transaction multiple times does not create additional business effects.
The synchronization worker sends a unique transaction identifier through the Idempotency-Key header.
However, sending an idempotency key alone does not guarantee idempotency. The receiving server must enforce it.
Let's build a minimal central API using FastAPI and SQLite.
Install the dependencies:
pip install fastapi uvicorn Create a file named server.py.
import json import sqlite3 from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel, Field app = FastAPI() class Sale(BaseModel): transaction_id: str store_id: str product_id: str quantity: int = Field(gt=0) total_cents: int = Field(ge=0) created_at: str with sqlite3.connect("central.db") as conn: conn.execute(""" CREATE TABLE IF NOT EXISTS sales ( transaction_id TEXT PRIMARY KEY, payload TEXT NOT NULL ) """) @app.post("/sales") def receive_sale( sale: Sale, idempotency_key: str = Header(...) ): if idempotency_key != sale.transaction_id: raise HTTPException( status_code=400, detail="Invalid idempotency key" ) payload = json.dumps( sale.model_dump(), sort_keys=True ) with sqlite3.connect( "central.db", timeout=10 ) as conn: conn.execute("BEGIN IMMEDIATE") existing = conn.execute(""" SELECT payload FROM sales WHERE transaction_id = ? """, (sale.transaction_id,)).fetchone() if existing: if existing[0] != payload: raise HTTPException( status_code=409, detail="Transaction payload conflict" ) return { "status": "already_processed", "transaction_id": sale.transaction_id } conn.execute(""" INSERT INTO sales (transaction_id, payload) VALUES (?, ?) """, ( sale.transaction_id, payload )) return { "status": "processed", "transaction_id": sale.transaction_id } Start the API:
uvicorn server:app --port 8000 In another terminal, start the synchronization worker:
python sync_worker.py The worker can now transmit locally recorded sales to the central database.
If the same transaction is received again with an identical payload, the server returns a successful response without inserting another sale.
If the same identifier arrives with different transaction data, the server returns a conflict.
In production, the transaction record and its associated inventory or financial effects must be committed atomically. Otherwise, duplicate side effects can still occur even when the sales table prevents duplicate records.
7. Handling Inventory Conflicts Across Offline Stores
Preventing duplicate transactions is only one part of the problem.
Consider a retailer with five units of a product available in a shared inventory pool.
Two stores temporarily lose connectivity.
Store A sells three units.
Store B also sells three units.
When both stores reconnect, the central system receives sales totaling six units, although only five were available.
This creates an inventory conflict.
A simplistic last-write-wins strategy might overwrite one store's inventory update with another.
That would be dangerous because it could discard valid sales activity.
Instead of synchronizing absolute inventory quantities, POS system should generally transmit individual business events.
For example:
{ "event_type": "sale_completed", "transaction_id": "TX-1001", "store_id": "STORE-001", "product_id": "SKU-1001", "quantity": 3 } The central system applies the inventory movement associated with the event.
This preserves the transaction history and makes reconciliation possible.
Depending on the retailer's business rules, the central system might:
- Record the sale and flag negative inventory.
- Generate an inventory discrepancy alert.
- Initiate a stock reconciliation workflow.
- Request manual review.
- Adjust available-to-sell quantities.
- Restrict future offline sales for selected products.
The correct strategy depends on whether inventory is store-specific, shared across locations, reserved for online orders, or managed through another fulfillment model.
A completed customer sale should not simply disappear because an inventory conflict occurred.
8. Choosing the Right Conflict Resolution Strategy
Different retail operations require different conflict resolution approaches.
Event-based reconciliation
Preserve each valid sales, return, transfer, or adjustment event and apply its business effects centrally.
This is particularly useful for inventory movements and financial transactions.
Optimistic concurrency control
Use record version numbers to detect when a product, customer record, or configuration has changed since the POS terminal last synchronized.
For example:
UPDATE products SET price_cents = ?, version = version + 1 WHERE product_id = ? AND version = ?; If no record is updated, the expected version is outdated or the record no longer exists.
The application can then retrieve the latest state and determine how to resolve the conflict.
Server-authoritative data
Certain information, such as approved pricing rules, tax configurations, and promotion definitions, may need to be controlled centrally.
Offline terminals can use approved cached configurations within defined validity periods.
However, previously completed sales should retain the pricing and tax information actually applied at the time of the transaction.
Manual reconciliation
Some conflicts cannot be resolved safely through automation.
Financial discrepancies, invalid refunds, conflicting transaction identifiers, and suspicious inventory adjustments may require human review.
The goal is not to eliminate every conflict. It is to detect conflicts and resolve them without losing valid business information.
9. Testing the Offline Synchronization Workflow
A reliable offline POS system should be tested under failure conditions, not just when everything works correctly.
Using our demonstration, we can simulate several scenarios.
Test 1: Network unavailable
Stop the central FastAPI server and record a new sale:
python pos.py The transaction should remain in the local synchronization queue.
Test 2: Connectivity restored
Restart the server:
uvicorn server:app --port 8000 Once the retry delay expires, the synchronization worker should transmit the pending transaction.
Test 3: Duplicate transaction delivery
After a successful synchronization, simulate a lost acknowledgment by resetting the queue entry.
UPDATE sync_queue SET status = 'pending', next_retry_at = 0 WHERE transaction_id = 'YOUR_TRANSACTION_ID'; The server should recognize the existing transaction and return a successful response without creating another sales record.
Test 4: Conflicting transaction data
Resend an existing transaction identifier with a modified quantity or total.
The server should return HTTP 409, and the worker should mark the transaction as a conflict.
Test 5: Application restart
Stop and restart the synchronization worker while transactions are pending.
Because the queue is stored in SQLite rather than application memory, pending transactions should remain available for processing.
These tests help validate transaction durability, retry behavior, duplicate prevention, and conflict detection.
10. Handling Offline Payments Securely
Offline transaction recording and offline payment authorization are not the same thing.
A POS application can record a sale locally, but that does not mean it can independently authorize a card payment without network connectivity.
Offline card acceptance depends on the payment terminal, payment processor, supported payment methods, transaction limits, and merchant risk policies.
Developers should avoid storing sensitive payment information such as full card numbers or security codes in local synchronization queues.
Instead, the POS system should integrate with approved payment solutions and retain only permitted transaction references and payment status information.
A production system should also distinguish between completed sales, authorized payments, pending payment confirmation, and failed payments.
This distinction is essential for accurate financial reconciliation.
11. Monitoring and Observability
An offline synchronization system should provide visibility into its operational health.
Useful metrics include:
- Number of pending transactions.
- Age of the oldest unsynchronized transaction.
- Synchronization success rate.
- Retry frequency.
- API response latency.
- Number of unresolved conflicts.
- Time since the last successful synchronization.
- Transactions requiring manual review.
For example, a store manager might receive an alert when transactions remain unsynchronized beyond an acceptable time limit.
Technical teams can use these metrics to identify connectivity problems, API failures, or synchronization bottlenecks.
Logging should include transaction identifiers and processing outcomes without exposing sensitive customer or payment information.
12. Production Considerations
The implementation in this tutorial demonstrates the core synchronization architecture.
A production-grade retail POS system would also need to address:
- Local database encryption and access controls.
- Secure API authentication and HTTPS.
- Device identity and store-level authorization.
- Multi-item sales and transaction sequencing.
- Returns, refunds, exchanges, and voided transactions.
- Local inventory reservations and availability rules.
- Tax and pricing configuration synchronization.
- Atomic queue claiming for concurrent workers.
- Dead-letter queues and controlled transaction replay.
- Database backups and disaster recovery.
- Payment reconciliation and audit trails.
- Clock differences between POS terminals and central servers.
Another important consideration is that transaction delivery may occur more than once.
Rather than assuming exactly-once network delivery, developers should design for at-least-once delivery with idempotent processing.
This approach makes synchronization more resilient to interruptions and ambiguous network failures.
Conclusion
Building an offline-first POS system involves much more than detecting whether an internet connection is available.
It requires an architecture that preserves local transactions, synchronizes them reliably, handles temporary failures, prevents duplicate business effects, and resolves conflicting information without losing valid sales records.
Persistent synchronization queues, transactional outbox patterns, exponential backoff, idempotent APIs, and event-based reconciliation provide a strong foundation for reliable retail transaction processing.
The most important principle is simple:
Network connectivity should determine when a transaction is synchronized, not whether a valid local transaction is preserved.
For developers building distributed retail applications, designing for failure from the beginning is what makes an offline POS system dependable when stores need it most.
How are you handling offline synchronization in your applications? Are you using persistent local queues, event-driven architectures, or another approach to conflict resolution?
