RFID to ERP: Event-Driven Warehouse Edge-to-Enterprise Pipeline
An industrial-grade, zero-trust, event-driven tracking and ERP integration pipeline designed to bridge the gap between noisy physical radio-frequency hardware bursts and transactional enterprise accounting ledgers (SAP S/4HANA EWM, Odoo, and Zoho Inventory). Engineered with SQLite store-and-forward edge buffering, distributed Redis debouncing, deterministic SHA-256 idempotency barriers, and FastMCP autonomous AI agent tooling.
Industrial SLA & Performance
:8001/metrics and visualised in Grafana.
Physics vs. Transactional Reality
In a logistics center, forklifts travel at 15 km/h through high-bay aisles lined with steel racks that reflect radio waves like a hall of mirrors. Mounted industrial UHF readers energize passive silicon tags, emitting up to 300 raw antenna reads per second.
Connecting those raw antenna bursts directly to an ERP triggers instant disaster: API rate limits blow out, duplicate inventory movements corrupt financial ledgers, and database row locks deadlock across concurrent worker threads. The warehouse forklift drivers are forced to halt while engineers untangle corrupt database states.
Asynchronous, Zero-Trust Decoupling
Our pipeline completely separates physical hardware bursts from enterprise transactional databases. Edge gateways spool scans to local SQLite during network drops, distributed Redis Sorted Sets aggregate passage events within 2.5s sliding windows, and NATS JetStream push consumers deliver sanitized payloads with SHA-256 idempotency locks.
Credentials remain Fernet-encrypted at rest in PostgreSQL and are decrypted only into ephemeral worker RAM. Transient outages are protected by exponential backoff with randomized jitter and routed to an actionable, replayable Dead Letter Queue (DLQ).
End-to-End System Topology
The pipeline spans physical dock gates, edge compute gateways, central message brokers, worker containers, and operations consoles:
[ UHF RFID Portal ] (Antennas + Optical GPI Break-Beams)
│ (Burst of EPC Gen2 scans)
│
[ Edge Gateway ] (Local SQLite Store-and-Forward Spooler)
│
│ NATS core publish (`rfid.raw.events.>`)
│
[ Stage 1: Edge Enrichment & Windowing ]
├─ GS1 Tag Decoder (SSCC-96, SGTIN-96, GRAI-96)
├─ Directional Resolution (Deterministic Portal Metadata)
├─ Distributed Sliding Window (Redis ZSET, 2.5s debounce)
└─ Deterministic Idempotency Key (SHA-256)
│
│ NATS JetStream publish (`RFID_DELIVERY` stream)
│
[ Stage 2: Secure Delivery & ERP Dispatch ]
├─ NATS JetStream PUSH Queue Consumer (`secure_delivery_processor`)
├─ Database Idempotency Barrier (PostgreSQL)
├─ Ephemeral RAM Credential Decryption (Fernet Zero-Trust)
├─ Pluggable ERP Adapters (SAP EWM, Odoo, Zoho, Webhooks)
└─ Exponential Backoff, Jitter & Dead Letter Queue (`rfid.dlq.*`)
│
│
[ Operations & Control Plane ]
├─ Django 5 Control Plane & Dark Operations Dashboard
├─ 1-Click DLQ Replay Engine
├─ SRE Observability (Prometheus `:8001/metrics` + Grafana)
└─ FastMCP Model Context Protocol Server (AI Agent Tooling)
Workers execute asynchronously with non-blocking event loops, enabling linear scaling simply by adding Docker replicas to the NATS JetStream queue group.
Technical Specifications
| RFID Protocol | UHF EPC Gen2 (ISO/IEC 18000-6C) @ 860–960 MHz |
| Standard Decoders | GS1 SSCC-96, SGTIN-96, GRAI-96 |
| Edge Storage | SQLite 3 (FIFO Store-and-Forward Spooler) |
| Debounce Engine | Redis Sorted Sets (ZSET) with 2.5s Reaper |
| Streaming Bus | NATS JetStream (Push Durable Queue Groups) |
| Security / Secrets | Fernet AES-128-CBC + HMAC-SHA256 (Ephemeral RAM) |
| Database Backend | PostgreSQL 16 (Idempotency Barrier & Audit Logs) |
| Target ERPs | SAP S/4HANA EWM, Odoo 17+, Zoho Inventory |
| Observability | Prometheus :8001/metrics, Alerts, Grafana |
| AI Agent Tooling | FastMCP (Model Context Protocol Specification) |
Core Architectural Pillars
Explore how each layer in the pipeline solves a specific industrial failure mode with battle-tested software engineering patterns.
Store-and-Forward SQLite Spooler
Eliminates scan loss when warehouse Wi-Fi fluctuates or uplink cables disconnect. If NATS is unreachable, edge gateways seamlessly divert incoming tag bursts to a local SQLite database in FIFO sequence. A background daemon flushes backlogged records the millisecond connectivity restores.
GS1 EPC Bit-Level Decoding
Opaque 96-bit hexadecimal tags are decoded into standard global supply chain entities before leaving the edge. The system parses bit headers to extract company prefixes, item references, and serials for SSCC-96 (pallets), SGTIN-96 (cartons), and GRAI-96 (returnable totes).
Redis ZSET Sliding Windows
Centralized debouncing in Redis Sorted Sets indexed by epoch timestamp. Workers horizontally scale without losing state across processes. A background reaper settles windows after 2.5s of quietness, computing a deterministic SHA-256 hash across gate ID and sorted tags.
NATS JetStream Push Consumers
High-throughput warehouse logistics requires sub-millisecond dispatching. NATS JetStream push subscriptions deliver settled messages directly to consumer queue groups, auto-balancing loads across replicas with manual acknowledgments only after successful ERP recording.
Zero-Trust Ephemeral Decryption
Wire messages carry only non-sensitive routing IDs. ERP authentication tokens and passwords remain Fernet AES-128 encrypted in PostgreSQL. At dispatch time, the worker pulls and decrypts credentials directly into ephemeral RAM, closing the window for credential exfiltration.
Pluggable Multi-ERP Adapters
Custom adapters handle enterprise nuances: SAP S/4HANA EWM two-step CSRF token handshakes over OData v4, Odoo stock moves via JSON-RPC 2.0, and Zoho Inventory OAuth 2.0 token renewals protected against worker stampedes using distributed Redis mutex locks.
Exponential Backoff & DLQ
Downstream ERP throttles trigger exponential backoff with randomized jitter to prevent thundering herds.
If retries exhaust, transactions are logged in PostgreSQL with status DEAD_LETTER and routed
to a dedicated NATS DLQ subject for manual or automated re-drive.
Prometheus & Grafana SRE Metrics
The Stage 2 worker exposes Prometheus metrics directly on :8001/metrics. SRE teams track ERP
latency histograms, throughput counters by destination, DLQ count, and alerts for
HighERPLatencyThresholdExceeded in real-time Grafana dashboards.
FastMCP AI Agent Control Plane
Implements the Model Context Protocol (MCP) using FastMCP. Autonomous AI support agents can inspect dead letter records, query portal telemetry, diagnose ERP rejection causes, and re-dispatch failed messages directly using natural language prompts.
System Screenshots & Operations Gallery
Click any screenshot to open the interactive carousel lightbox with zoom, pan, and full-resolution controls.
Secure Operator Authentication
Role-based authentication to the Django 5 Operations Control Plane for warehouse managers and integration engineers.
Site Administration & Directory
Directory navigation, authorization groups, and quick launch triggers for the live RFID-to-ERP operations console.
Live Telemetry & DLQ Replay
Real-time gate passage telemetry, active routing destinations (SAP, Odoo, Zoho), settlement statuses, and 1-Click DLQ replay.
Prometheus SRE Alerting Rules
Active rule evaluation for
HighERPLatencyThresholdExceeded and pipeline alerts safeguarding downstream ERP health.
Raw Prometheus /metrics Feed
Stage 2 worker exposing multi-dimensional transaction counters, duration histograms, garbage collection, and DLQ metrics.
Active Scrape Targets Status
Prometheus cluster target monitoring confirming 100% UP
availability for distributed delivery workers on port 8001.
Grafana Operations Overview
Live portal passage velocity, Inbound/Outbound ratio, 100% dispatch success rate, DLQ diversion counts, and ERP latency percentiles.
Core Implementation Snippets
Review the real engineering patterns running inside the pipeline's production containers.
edge/edge_gateway.py
Offline Spooling
Store-and-Forward Spool & Drain Logic
async def publish_or_spool(self, subject: str, payload_dict: dict):
"""Attempts immediate publish; falls back to local spool if offline."""
if not self.is_connected:
await self.connect_nats()
if self.is_connected:
try:
await self.nc.publish(subject, json.dumps(payload_dict).encode("utf-8"))
await self.nc.flush(timeout=2.0)
return
except Exception as e:
logger.warning(f"Publish failed ({e}). Switching to spooling.")
self.is_connected = False
await self.spool_event(subject, payload_dict)
When connection restores, an asynchronous drain sweep reads records from SQLite in strict chronological FIFO order and publishes them to NATS before deleting rows.
services/stage1_enrichment.py
Sliding Window
Atomic Sliding Window Buffer (Redis ZSET)
async def handle_raw_event(self, msg):
data = json.loads(msg.data.decode("utf-8"))
mac = data.get("hardware_mac_id")
tags = data.get("tags", [])
now_ms = int(time.time() * 1000)
gate_info = await self.get_gate_for_mac(mac)
zset_key = f"rfid:window:{gate_info['gate_id']}:tags"
meta_key = f"rfid:window:{gate_info['gate_id']}:meta"
async with self.redis.pipeline(transaction=True) as pipe:
for tag in tags:
pipe.zadd(zset_key, {tag: now_ms})
pipe.hset(meta_key, mapping={"last_seen_ms": now_ms, "direction": gate_info["direction"]})
pipe.sadd("rfid:active_windows", str(gate_info["gate_id"]))
await pipe.execute()
Using Redis pipelines allows high-volume bursts to update timestamps atomically without acquiring expensive distributed locks.
services/stage2_delivery.py
JetStream Push
Durable JetStream Push Queue Subscriber
# Bind durable push subscriber on delivery stream with queue group
self.sub = await self.js.subscribe(
"rfid.delivery.>",
queue="secure_delivery_processor",
durable="secure_delivery_processor",
cb=self.process_message,
manual_ack=True,
)
Combining queue and durable guarantees push-based load balancing across worker
instances while ensuring zero message loss with manual_ack=True.
mcp_service/server.py
FastMCP Tooling
Model Context Protocol AI Agent Tools
@mcp.tool()
async def replay_dead_letter_record(record_id: str) -> str:
"""Replays an exhausted DLQ transaction back to the delivery stream."""
rec = await sync_to_async(DeadLetterRecord.objects.get)(id=record_id)
if rec.is_replayed:
return f"Record {record_id} was already replayed."
await publish_replay_to_nats(rec)
rec.is_replayed = True
rec.replayed_at = timezone.now()
await sync_to_async(rec.save)()
return f"Successfully replayed transaction {record_id} to NATS JetStream."
Allows autonomous LLM agents (Claude, Gemini, GPT) to assist human supervisors by diagnosing errors and re-driving failed messages through conversation.
Key Architectural Takeaways
Antennas scan tags and gateways spool to SQLite. Never burden edge gateways with complex ERP business logic or external dependencies.
Physical radio bounce is repetitive. Centralizing debouncing in Redis Sorted Sets guarantees horizontally scalable sliding window aggregation.
Combining portal gate ID, sorted tags, and settled epoch with SHA-256 guarantees that every unique passage produces exactly one immutable signature.
Never transmit plaintext passwords across brokers. Encrypt with Fernet at rest and decrypt exclusively into worker RAM during HTTP dispatch.
Failures are first-class citizens. Divert exhausted retries to searchable DLQ topics with full snapshots, ready for 1-click or AI agent replay.
Model Context Protocol (FastMCP) empowers LLM agents to act as tier-1 support engineers, querying logs and triggering replays in natural language.
From RF Bursts to Financial Ledgers: Architecture of an Event-Driven RFID-to-ERP Pipeline
Read the full in-depth engineering breakdown covering SQLite edge store-and-forward spooling, bit-level GS1 decoding, Redis ZSET sliding window debouncing, NATS JetStream push queues, zero-trust Fernet RAM encryption, and FastMCP AI agent operations.