UHF EPC Gen2 NATS JetStream Redis ZSET Sliding Window Fernet In-RAM Zero-Trust SAP EWM / Odoo / Zoho FastMCP AI Operations

From RF Bursts to Financial Ledgers: Architecture of an Event-Driven RFID-to-ERP Pipeline

Félix Pupo Pérez Félix Pupo Pérez
October 5, 2026
22 min read
Production Architecture & System Design
Project Showcase: RFID to ERP Pipeline Production Blueprint

A companion project with a live operations dashboard, Prometheus/Grafana metrics, and FastMCP model context protocol agent tools. Explores how to safely connect 300 raw RF scans per second to SAP S/4HANA EWM, Odoo, and Zoho Inventory.

Python 3.11+ NATS JetStream Redis 7 & PostgreSQL 16 Prometheus & Grafana

In modern warehouse distribution centers, physics and enterprise accounting exist in two completely incompatible universes. On one side, physical forklifts roar through steel dock doors at 15 km/h, energizing hundreds of passive UHF RFID tags and emitting chaotic bursts of up to 300 raw antenna reads every second. On the other side sits your core enterprise ledger—whether SAP S/4HANA EWM, Odoo, or Zoho Inventory—where every transaction demands strict serializability, ACID consistency, and careful rate-limiting.

When teams attempt to bridge these two worlds with simple HTTP webhooks or direct database inserts, the result is almost comical: ERP connection pools exhaust in seconds, downstream accounting tables deadlock, and duplicate physical reads cause ghost inventory postings that take weeks of manual financial reconciliations to untangle.

To solve this, we designed and built an asynchronous, zero-trust, event-driven integration pipeline. It isolates raw radio-frequency noise from transactional enterprise ledgers using local SQLite store-and-forward edge buffers, distributed Redis Sorted Sets (ZSET) for sliding window debouncing, NATS JetStream push-queue subscriptions, ephemeral in-RAM Fernet cryptography, and an autonomous FastMCP Model Context Protocol support layer.

This article walks through the exact architectural decisions, technical trade-offs, and production code snippets that make this pipeline capable of guaranteeing zero data loss, sub-millisecond edge ingestion, and 100% deterministic idempotency.


01. The Warehouse Dilemma: Physics vs. Transactional Consistency

To understand why this architecture was built, you have to look at the physical environment of an industrial warehouse. High-bay distribution aisles are constructed with towering galvanized steel racks. These racks act as colossal radio-frequency reflectors, creating a multipath propagation nightmare for ultra-high frequency (UHF) radio waves in the 860–960 MHz range (EPC Gen2 / ISO 18000-6C).

When a forklift passes through an automated dock portal, its four antenna panels emit continuous RF energy to energize the passive microchips embedded in pallet and carton labels. Consider what happens in a span of 3 seconds:

  • Radio Multipath Flutter: The same tag bounces in and out of the antenna field, producing 20 to 50 distinct scan packets with oscillating RSSI (Received Signal Strength Indicator) values between -40 dBm and -75 dBm.
  • Cross-Portal Bleed: Antennas mounted at Door #4 often pick up reflections from a pallet being unloaded at Door #5, creating false-positive ghost scans.
  • Burst Density: A single forklift loaded with 40 cartons (each with an individual serialized SGTIN-96 tag) on a master pallet (with an SSCC-96 container tag) generates roughly 900 raw tag events during a single 3-second drive-through.
  • Network Brittleness: Forklifts frequently obstruct line-of-sight Wi-Fi access points, and warehouse Ethernet switches occasionally reboot or suffer transient cable cuts from equipment collisions.
The Direct Posting Anti-Pattern

If an edge RFID reader simply hits an ERP REST or OData API synchronously for every raw scan, the ERP instantly crashes. 300 POST requests/second easily blow out SAP OData work processes, exceed Zoho API daily quotas in less than 20 minutes, and trigger PostgreSQL row lock contention on Odoo's stock.quant tables, bringing all warehouse dispatch screens to a dead halt.

Therefore, our fundamental architectural rule is: Physical edge telemetry must never touch enterprise transactional databases directly. An intermediate, highly decoupled, multi-stage event processing pipeline is mandatory.

02. End-to-End System Topology: The Multi-Stage Pipeline

The system is divided into three distinct decoupled stages, each with a single responsibility, isolated failure domain, and tailored persistence mechanism:

System Architecture Topology
  [ UHF RFID Dock Portal ]
   ├─ 4x Impinj / Zebra Antennas (860–960 MHz, EPC Gen2)
   └─ Optical GPI Photo-Eye Break-Beams (Passage Direction)
           │
           │ Hardware TCP / LLRP raw tag bursts
           │
  [ Stage 0: Industrial Edge Gateway ]
   ├─ Python asyncio Event Loop
   ├─ Local SQLite 3 FIFO Spooler (Store-and-Forward on Wi-Fi drop)
   └─ NATS Core Client (`rfid.raw.events.>`)
           │
           │ Core NATS Publish (Ephemeral, Sub-millisecond)
           │
  [ Stage 1: Enrichment & Windowing Service ]
   ├─ GS1 Bit-Level Decoder (SSCC-96 Pallets, SGTIN-96 Cartons, GRAI-96 Totes)
   ├─ Portal Directional Resolution (Optical GPI Trigger Correlation)
   ├─ Redis Sorted Sets (ZSET) 2.5s Sliding Window Debounce Buffer
   ├─ Window Reaper Daemon (Silence detection > 2500ms)
   └─ Deterministic SHA-256 Idempotency Key Generation
           │
           │ NATS JetStream Durable Publish (`RFID_DELIVERY` stream)
           │
  [ Stage 2: Secure Delivery & ERP Dispatch Workers ]
   ├─ JetStream Push Queue Consumer (`secure_delivery_processor`)
   ├─ PostgreSQL Idempotency Barrier (Atomic status check)
   ├─ Zero-Trust Credential Decryption (Fernet AES-128 directly into RAM)
   ├─ Pluggable Multi-ERP Adapters:
   │    ├─ SAP S/4HANA EWM (Two-step CSRF Token handshake + OData v4)
   │    ├─ Odoo 17+ (Native JSON-RPC 2.0 `stock.picking` execution)
   │    └─ Zoho Inventory (OAuth 2.0 with Redis Mutex Token Lock)
   ├─ Exponential Backoff with Full Randomized Jitter
   └─ Dead Letter Queue (DLQ) Routing (`rfid.dlq.*`) & PostgreSQL Audit
           │
           │
  [ Operations, Observability & AI Agent Control Plane ]
   ├─ Django 5 Dark Operations NOC & 1-Click DLQ Replay Engine
   ├─ Prometheus Metrics Scraper on `:8001/metrics`
   ├─ Grafana Operations Telemetry Dashboards
   └─ FastMCP Model Context Protocol Server (AI Autonomous Diagnostics)

Notice how the data transforms as it travels down the pipe:

  1. Raw Scans (Hardware Level): Opaque 96-bit hex strings emitted hundreds of times per second without semantic context.
  2. Enriched Passages (Settled Level): Decoded GS1 entities grouped by physical dock door, timestamp window, and confirmed directional intent (e.g. "Forklift 3 unloaded Pallet SSCC 061414112345678908 into Aisle 4").
  3. Transactional Dispatches (Enterprise Level): Sanitized, authenticated, single-execution ERP movements recorded against SAP, Odoo, or Zoho with guaranteed idempotency and audit logs.

03. Stage 0: Edge Resilience with SQLite Store-and-Forward

The edge gateway runs on an industrial DIN-rail PC (such as an Advantech or Raspberry Pi CM4 Industrial Gateway) installed directly adjacent to the portal antennas.

In many IoT architectures, developers assume the local network is always healthy. In a real warehouse, dock doors get bumped, switches lose power during maintenance, and heavy metal cargo containers temporarily wipe out 5 GHz Wi-Fi signals.

To make the edge resilient, we implemented the Store-and-Forward Spooling Pattern:

edge/edge_gateway.py: Store-and-Forward Publisher
import asyncio
import json
import logging
import sqlite3
import time
from typing import Dict, Any
import nats

logger = logging.getLogger("edge_gateway")

class EdgeGateway:
    def __init__(self, db_path: str, nats_url: str):
        self.db_path = db_path
        self.nats_url = nats_url
        self.nc = None
        self.is_connected = False
        self._init_sqlite()

    def _init_sqlite(self):
        """Initializes a local FIFO spooling database with WAL journal mode."""
        with sqlite3.connect(self.db_path) as conn:
            conn.execute("PRAGMA journal_mode=WAL;")
            conn.execute("""
                CREATE TABLE IF NOT EXISTS spool_queue (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    subject TEXT NOT NULL,
                    payload TEXT NOT NULL,
                    created_at REAL NOT NULL
                );
            """)
            conn.commit()

    async def connect_nats(self):
        try:
            self.nc = await nats.connect(
                self.nats_url,
                reconnect_time_wait=2.0,
                max_reconnect_attempts=-1,
                error_cb=self._on_nats_error,
                reconnected_cb=self._on_nats_reconnected,
            )
            self.is_connected = True
            logger.info("Successfully connected to NATS message broker.")
            # Trigger background drain of any offline spooled scans
            asyncio.create_task(self.drain_spool())
        except Exception as e:
            self.is_connected = False
            logger.warning(f"NATS unavailable ({e}). Gateway operating in OFFLINE SPOOL mode.")

    async def publish_or_spool(self, subject: str, payload: Dict[str, Any]):
        """Zero-loss edge publisher: immediate NATS publish or instant SQLite spool."""
        if not self.is_connected:
            await self.spool_event(subject, payload)
            return

        try:
            raw_bytes = json.dumps(payload).encode("utf-8")
            await self.nc.publish(subject, raw_bytes)
            await self.nc.flush(timeout=0.5)
        except Exception as e:
            logger.warning(f"Publish failed ({e}). Diverting event to local SQLite spool.")
            self.is_connected = False
            await self.spool_event(subject, payload)

    async def spool_event(self, subject: str, payload: Dict[str, Any]):
        """Persists scan event to local SSD in strictly ordered FIFO sequence."""
        payload_str = json.dumps(payload)
        now = time.time()
        loop = asyncio.get_running_loop()
        await loop.run_in_executor(None, self._write_spool_sync, subject, payload_str, now)
        logger.debug(f"Event spooled locally to SQLite: {subject}")

    def _write_spool_sync(self, subject: str, payload_str: str, created_at: float):
        with sqlite3.connect(self.db_path) as conn:
            conn.execute(
                "INSERT INTO spool_queue (subject, payload, created_at) VALUES (?, ?, ?);",
                (subject, payload_str, created_at)
            )
            conn.commit()

    async def drain_spool(self):
        """Flushes backlogged records chronologically once NATS connection is restored."""
        while self.is_connected:
            loop = asyncio.get_running_loop()
            rows = await loop.run_in_executor(None, self._fetch_batch_sync, 100)
            if not rows:
                break

            logger.info(f"Draining {len(rows)} backlogged events from edge spool...")
            for row_id, subject, payload_str in rows:
                try:
                    await self.nc.publish(subject, payload_str.encode("utf-8"))
                    await loop.run_in_executor(None, self._delete_row_sync, row_id)
                except Exception as e:
                    logger.error(f"Drain failed midway ({e}); aborting drain cycle.")
                    self.is_connected = False
                    return
            await self.nc.flush(timeout=2.0)
            await asyncio.sleep(0.05)

Optical Break-Beam GPI Directionality Triggers

A major trap in RFID deployments is trying to determine whether a forklift is entering or exiting based solely on RFID phase angles or antenna RSSI strength. Because warehouse metal shelving bounces RF signals unpredictably, RSSI Doppler calculations frequently report false directions.

We solved this with simple, unshakeable physics: dual optical photo-eye break-beams connected to the edge gateway's General Purpose Inputs (GPI).

  • Inbound Motion: Beam A breaks first, followed by Beam B within 1500ms. Direction is tagged INBOUND.
  • Outbound Motion: Beam B breaks first, followed by Beam A. Direction is tagged OUTBOUND.
  • Static Read: If tags are scanned without optical beam interruption, the read is discarded or marked as ambient background noise.

04. Stage 1: Bit-Level GS1 Decoding & Redis ZSET Sliding Windows

Once raw packets reach the central ingestion service via core NATS (rfid.raw.events.>), Stage 1 performs two critical operations: semantic decoding and distributed debouncing.

GS1 EPC Bit-Level Decoding

UHF RFID tags store data as hexadecimal strings representing 96-bit or 128-bit EPC Gen2 standard structures. Before transmitting to an ERP, the raw bits must be sliced into globally recognized supply chain entities:

EPC Scheme Header (Bits) Decoded Fields Supply Chain Purpose
SSCC-96 00110001 (0x31) Filter Value, Company Prefix, Extension Digit, Serial Reference Logistic Pallets & Master Containers (Standard GS1-128 barcode equivalent)
SGTIN-96 00110000 (0x30) Company Prefix, Item Reference (GTIN/EAN), Serial Number Individual commercial consumer cartons and item-level units
GRAI-96 00110011 (0x33) Company Prefix, Asset Type, Serial Number Reusable transport assets (plastic totes, roll cages, metal crates)

The Debounce Engine: Why Redis Sorted Sets (ZSET)?

As the forklift rolls past the antennas, a single carton tag will be read 30 times in 2.5 seconds. How do you know when the passage has ended?

We evaluated three architectural approaches for window debouncing:

Approach Pros Cons Verdict
In-Memory Python Dicts Extremely fast, zero dependencies Cannot share state across worker processes; all state lost on pod restart Rejected
Apache Flink / Kafka Streams Native sliding windows, huge throughput Extremely heavy JVM footprint, operational complexity, over-engineering for single-site gates Rejected
Redis Sorted Sets (ZSET) Atomic millisecond scores, microsecond lookups, clusterable across workers Requires an external daemon reaper task Selected

Here is how our atomic sliding window buffer works in practice:

services/stage1_enrichment.py: Redis ZSET Windowing
async def handle_raw_event(self, msg):
    """Accumulates incoming raw tag reads into an atomic Redis sliding window."""
    data = json.loads(msg.data.decode("utf-8"))
    mac = data.get("hardware_mac_id")
    raw_tags = data.get("tags", [])
    now_ms = int(time.time() * 1000)

    # 1. Resolve portal hardware mapping and optical beam direction
    gate_info = await self.get_gate_for_mac(mac)
    gate_id = gate_info["gate_id"]
    direction = gate_info["direction"]

    # 2. Decode GS1 structures (SSCC-96, SGTIN-96, GRAI-96)
    enriched_tags = [self.gs1_decoder.decode(tag) for tag in raw_tags]

    # 3. Push to Redis Sorted Set where Score = Timestamp (ms)
    zset_key = f"rfid:window:{gate_id}:tags"
    meta_key = f"rfid:window:{gate_id}:meta"

    async with self.redis.pipeline(transaction=True) as pipe:
        for tag in enriched_tags:
            # Serialized JSON payload stored as member, epoch as score
            pipe.zadd(zset_key, {json.dumps(tag): now_ms})

        pipe.hset(meta_key, mapping={
            "last_seen_ms": now_ms,
            "direction": direction,
            "door_name": gate_info["door_name"]
        })
        pipe.sadd("rfid:active_windows", gate_id)
        await pipe.execute()

The Window Reaper & Deterministic SHA-256 Idempotency Key

A background asyncio reaper runs every 500ms, checking rfid:active_windows. If now_ms - last_seen_ms > 2500ms, it means the forklift has completely passed beyond the antenna range. The window is settled.

The reaper extracts all tags from the ZSET, sorts them alphabetically by EPC to guarantee consistent order, and computes an immutable SHA-256 Idempotency Key:

# Deterministic signature calculation
tag_epcs_sorted = sorted([t["epc"] for t in window_tags])
hash_input = f"{gate_id}:{settled_epoch_second}:{':'.join(tag_epcs_sorted)}"
idempotency_key = hashlib.sha256(hash_input.encode("utf-8")).hexdigest()

This signature is published directly to the NATS JetStream stream named RFID_DELIVERY under subject rfid.delivery.<portal_id>.

05. Stage 2: NATS JetStream Delivery & Zero-Trust In-RAM Cryptography

Stage 2 is the workhorse of the pipeline. It is responsible for consuming settled passage events and safely recording them in target enterprise ERP systems.

Why NATS JetStream Push Queue Groups?

Unlike traditional message brokers (like RabbitMQ) or event logs (like Kafka), NATS JetStream offers a sweet spot for industrial edge-to-enterprise integration:

  • Zero Dependencies: Single static binary with minuscule memory footprint (~30MB RAM).
  • Push-Based Durable Consumers: Workers don't waste CPU cycles polling. NATS pushes messages down to active workers instantly.
  • Queue Groups for Horizontal Scaling: By subscribing with queue="secure_delivery_processor", NATS automatically load-balances delivery messages across as many worker container replicas as you spawn.
  • Manual Acknowledgments: The worker invokes await msg.ack() only after the downstream ERP confirms the transaction with HTTP 200/201. If the worker crashes mid-flight, JetStream re-delivers the message to another replica.
services/stage2_delivery.py: NATS Push Subscription
# Durable JetStream Push Queue Subscription
self.sub = await self.js.subscribe(
    subject="rfid.delivery.>",
    queue="secure_delivery_processor",
    durable="secure_delivery_processor",
    cb=self.process_message,
    manual_ack=True,
)

Zero-Trust Security: Fernet Ephemeral In-RAM Decryption

In corporate IT networks, message buses are frequently monitored or inspected. Transmitting plaintext ERP API tokens or SAP administrative credentials across NATS subjects is an egregious security vulnerability.

Our pipeline adopts a Zero-Trust Architecture:

The Ephemeral RAM Pattern

Messages on NATS contain strictly public routing identifiers (e.g. destination_id: "SAP_PROD_EWM_01"). No API keys, client secrets, or passwords exist on the wire. When a worker receives a message, it queries the PostgreSQL credentials vault, decrypts the Fernet AES-128-CBC + HMAC-SHA256 cipher directly into a temporary local variable in RAM, executes the HTTPS request to the ERP, and allows Python's garbage collector to immediately discard the plaintext secret.

06. Pluggable ERP Adapters: Handling Real-World Quirks

Every ERP speaks a different dialect and comes with unique architectural idiosyncrasies. Our pipeline isolates these differences inside modular adapter classes adhering to a common interface: async def dispatch(self, passage_event) -> ERPResponse.

RFID Operations Control Plane Dashboard
Figure 1: Live RFID-to-ERP Operations Control Plane showing multi-destination routing (SAP, Odoo, Zoho) and DLQ status. 100% Dispatch SLA

1. SAP S/4HANA EWM (Extended Warehouse Management)

SAP S/4HANA exposes OData v4 endpoints for goods movement creation (API_WAREHOUSE_GOODS_MOVEMENT). However, SAP requires a mandatory two-step CSRF token handshake:

  1. Worker executes an initial GET /sap/opu/odata4/... with header x-csrf-token: fetch.
  2. SAP returns an encrypted CSRF token and sets session cookies (SAP_SESSIONID).
  3. Worker executes the actual POST /GoodsMovement, attaching both the extracted token and cookies.

2. Odoo ERP 17+

Odoo integration bypasses standard REST and connects via high-performance native JSON-RPC 2.0 (/jsonrpc). The adapter authenticates against common.authenticate, retrieves the user UID, and executes an atomic multi-step procedure on the stock.picking and stock.move.line models, concluding with button_validate to instantly update inventory balances and fiscal stock journals.

3. Zoho Inventory

Zoho uses OAuth 2.0 with short-lived bearer tokens (60-minute expiry). If five worker replicas suddenly discover their Zoho token has expired at the exact same millisecond, they will all hammer Zoho's token endpoint simultaneously—triggering an immediate account rate-limit lockout.

We solved this by wrapping Zoho token refresh in a Distributed Redis Mutex Lock:

adapters/zoho_adapter.py: Distributed Redis Mutex
async def get_valid_access_token(self) -> str:
    """Retrieves cached token or acquires distributed lock to perform refresh."""
    cached = await self.redis.get("oauth:zoho:access_token")
    if cached:
        return cached.decode("utf-8")

    # Acquire distributed lock using Redis SETNX with 10s TTL
    lock_acquired = await self.redis.set("lock:zoho:refresh", "1", nx=True, ex=10)
    if lock_acquired:
        try:
            new_token, expires_in = await self._call_zoho_refresh_api()
            # Cache in Redis with 60-second safety buffer before expiry
            await self.redis.set("oauth:zoho:access_token", new_token, ex=expires_in - 60)
            return new_token
        finally:
            await self.redis.delete("lock:zoho:refresh")
    else:
        # Another worker is refreshing; wait and back off
        await asyncio.sleep(1.0)
        return await self.get_valid_access_token()

07. Resilience: Exponential Backoff & Actionable Dead Letter Queues

In production, integrations do not fail cleanly. They fail partially, temporarily, and unpredictably. A resilient system must distinguish between two fundamental failure modes:

Transient Errors (Retryable)

HTTP 429 Too Many Requests, HTTP 503 Service Unavailable, TCP connection reset, DNS lookup timeout.

Strategy: Exponential backoff with randomized Full Jitter. Maximum 5 retry attempts over 60 seconds.

Permanent Rejections (Non-Retryable)

HTTP 400 Bad Request ("Unknown SKU: ABC-123"), HTTP 422 Unprocessable ("Storage bin aisle locked for physical audit").

Strategy: Immediate termination of retry loop. Divert transaction to the Dead Letter Queue (DLQ).

Exponential Backoff with Full Jitter Formula
# Full Jitter Backoff prevents thundering herds against recovering ERPs
sleep_duration = random.uniform(0, min(max_backoff, base_backoff * (2 ** attempt)))

The Dead Letter Queue (DLQ) Architecture

When a transaction exhausts all retry attempts or suffers a permanent schema rejection, the pipeline guarantees that the event is never silently dropped. The worker executes two atomic actions:

  1. Publishes the complete passage payload, error stack trace, and HTTP status code to NATS subject rfid.dlq.<target_erp> on stream RFID_DLQ.
  2. Inserts an unacknowledged record into the PostgreSQL dead_letter_records table with status DEAD_LETTER.
  3. Acknowledges the original message on JetStream with await msg.ack() so consumer queues continue processing incoming traffic without blockage.

From the Django Operations Dashboard, warehouse integration managers can inspect the exact reason for failure, correct the underlying ERP data (e.g. create the missing SKU or unlock the warehouse bin), and click 1-Click DLQ Replay to re-publish the transaction back to the delivery queue.

08. Production Observability: Prometheus & Grafana SRE Metrics

You cannot operate a high-volume warehouse pipeline blindly. The Stage 2 delivery worker exposes a native Prometheus metric scraping endpoint directly on :8001/metrics.

Prometheus Metrics Endpoint on port 8001
Figure 2: Raw Prometheus scrape endpoint exposing transaction counters and latency histograms.
Prometheus Alerting Rules Evaluation
Figure 3: Active Prometheus alerting rules safeguarding against downstream ERP latency spikes.

Core Production Prometheus Metrics

Metric Name Type Labels Description
rfid_events_processed_total Counter destination, status Total number of passage events delivered to ERPs (200 OK vs Error)
rfid_erp_delivery_duration_seconds Histogram destination HTTP round-trip latency percentiles (p50, p95, p99) for ERP calls
rfid_dlq_events_total Counter destination, error_category Cumulative transactions diverted to the Dead Letter Queue
rfid_active_windows Gauge gate_id Real-time count of debouncing windows currently open in Redis
Grafana Operations Telemetry Overview
Figure 4: Live Grafana dashboard tracking portal throughput, inbound/outbound ratio, and 100% delivery SLA. Zero DLQ Failures

Automated Prometheus Alerting Rule

To ensure Site Reliability Engineers (SREs) are notified before forklift drivers notice system slowdowns, Prometheus evaluates active rules every 15 seconds:

prometheus/alerting_rules.yml
groups:
  - name: rfid_pipeline_alerts
    rules:
      - alert: HighERPLatencyThresholdExceeded
        expr: histogram_quantile(0.95, sum(rate(rfid_erp_delivery_duration_seconds_bucket[5m])) by (le, destination)) > 5.0
        for: 2m
        labels:
          severity: critical
        annotations:
          summary: "ERP {{ $labels.destination }} latency exceeds 5.0 seconds"
          description: "95th percentile dispatch latency to {{ $labels.destination }} is {{ $value }}s over the last 5 minutes. Downstream ERP may be throttling."

      - alert: HighDeadLetterQueueRate
        expr: rate(rfid_dlq_events_total[5m]) > 0.05
        for: 1m
        labels:
          severity: warning
        annotations:
          summary: "DLQ ingestion rate elevated"
          description: "More than 5% of RFID passages are failing ERP dispatch and diverting to DLQ."

09. AI Agent Operations: The FastMCP Control Plane

One of the most modern architectural facets of this project is its native integration with Anthropic's Model Context Protocol (MCP) via Python's FastMCP.

In traditional software, when a batch of RFID passages lands in the DLQ, an on-call engineer must manually SSH into a bastion server, query PostgreSQL, decode raw JSON blobs, check ERP error logs, and run a curl command to re-drive the queue.

By wrapping our operations plane in an MCP server, autonomous AI agents (running in Claude Desktop, Gemini, or custom LangGraph supervisors) can act as tier-1 warehouse support engineers:

mcp_service/server.py: FastMCP Operational Toolset
from fastmcp import FastMCP
from asgiref.sync import sync_to_async
from django.utils import timezone
from core.models import DeadLetterRecord, PortalGate

mcp = FastMCP("RFID-ERP-Operations-Agent")

@mcp.tool()
async def get_system_health() -> dict:
    """Returns real-time pipeline status, active worker count, and DLQ depth."""
    dlq_count = await sync_to_async(DeadLetterRecord.objects.filter(is_replayed=False).count)()
    active_gates = await sync_to_async(PortalGate.objects.filter(is_active=True).count)()
    return {
        "status": "HEALTHY" if dlq_count < 10 else "DEGRADED",
        "active_portals": active_gates,
        "unresolved_dlq_records": dlq_count,
        "timestamp": timezone.now().isoformat()
    }

@mcp.tool()
async def diagnose_failed_transaction(record_id: str) -> dict:
    """Fetches full error context, raw tags, and ERP response for a DLQ event."""
    rec = await sync_to_async(DeadLetterRecord.objects.get)(id=record_id)
    return {
        "record_id": str(rec.id),
        "target_erp": rec.destination,
        "error_message": rec.error_message,
        "http_status": rec.http_status_code,
        "passage_tags": rec.payload.get("tags", []),
        "occurred_at": rec.created_at.isoformat()
    }

@mcp.tool()
async def replay_dead_letter_record(record_id: str) -> str:
    """Replays an exhausted DLQ transaction back to the active 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 at {rec.replayed_at}."

    await publish_replay_to_nats(rec.payload, rec.destination)
    rec.is_replayed = True
    rec.replayed_at = timezone.now()
    await sync_to_async(rec.save)()
    return f"Successfully re-published transaction {record_id} to NATS JetStream."

Real-World Autonomous AI Agent Interaction

Here is what happens when a warehouse supervisor notices an alert and prompts their AI support assistant:

AI Agent Diagnostic Dialogue
Operator: "Claude, why did Dock Door 4 fail to record its last pallet movement in SAP?"

AI Agent: *Calls diagnose_failed_transaction(record_id="dlq_8f912c")*
AI Agent: "Dock Door 4's delivery failed because SAP S/4HANA EWM rejected the goods
movement with HTTP 422: 'Storage Bin B-04-12 is currently locked for cycle count.'
The pallet contains 30 units of SKU 784-01-A (SSCC: 061414112345678908).

Would you like me to check if the cycle count lock has been cleared in SAP and
replay the transaction?"

Operator: "Yes, the cycle count is finished. Replay it."

AI Agent: *Calls replay_dead_letter_record(record_id="dlq_8f912c")*
AI Agent: "Transaction dlq_8f912c successfully re-published to NATS JetStream.
Downstream SAP worker confirmed goods movement posting: Material Document #4900192841."

10. Architectural Trade-Offs & Production Checklist

Designing distributed systems is never about finding the "perfect" technology; it is about choosing the right compromises for your domain constraints.

Decision What We Chose What We Rejected Rationale & Trade-off
Edge Persistence SQLite 3 (WAL Mode) In-Memory Ring Buffers Power outages and cable cuts must not lose scans. SQLite WAL writes in <1ms while surviving hardware restarts.
Debounce State Redis Sorted Sets (ZSET) Python Process Memory Enables multi-process horizontally scalable workers to share identical debouncing windows without losing state.
Streaming Engine NATS JetStream Apache Kafka Kafka's JVM footprint and partition rebalancing overhead are excessive for warehouse gateway deployments. NATS compiles to a single binary with sub-millisecond latencies.
Credentials Security Fernet In-RAM Decryption Plaintext NATS Payload Zero-trust posture. Message buses should be treated as untrusted transport mediums. Credentials exist in RAM only for the millisecond of the HTTP call.
Failure Handling Searchable DLQ + FastMCP Infinite Retries Infinite retries cause head-of-line blocking and poison downstream queues. DLQs isolate broken records without slowing healthy pallet passages.
10-Point Industrial Pipeline Deployment Checklist
  1. Enable SQLite PRAGMA journal_mode=WAL; on edge gateways to prevent database locking during concurrent RFID scans.
  2. Calibrate optical photo-eye timeout windows (1.5s to 2.5s) to match the forklift transit speed in your warehouse aisles.
  3. Configure NATS JetStream max_age, storage=file, and replicas=3 for high-availability clusters.
  4. Bind NATS subscriptions with both queue and durable parameters to guarantee push-based round-robin load distribution.
  5. Set manual_ack=True on delivery workers and acknowledge only after receiving an affirmative HTTP response from the ERP.
  6. Ensure all tags are sorted alphabetically before computing the passage SHA-256 idempotency key.
  7. Store Fernet cryptographic master keys in secure OS environment variables or Kubernetes secrets, never committed to source code.
  8. Implement distributed Redis mutex locks (SET NX EX) on OAuth 2.0 token refresh workflows.
  9. Configure Prometheus alert evaluations for 95th percentile ERP latency exceeding 5.0 seconds.
  10. Test the 1-Click DLQ replay engine in a staging environment with simulated ERP 503 service unavailable outages.

11. Conclusion

Bridging the gap between the chaotic, noisy physical world of industrial RFID hardware and the rigorous, ACID-compliant realm of enterprise ERPs is one of the most rewarding challenges in distributed systems engineering.

By treating the edge as a resilient spooler, utilizing distributed Redis Sorted Sets for atomic sliding debounces, relying on NATS JetStream for durable sub-millisecond dispatching, and empowering operations teams with FastMCP AI agent tooling, this architecture proves that you can ingest 300 raw RF scans per second while maintaining 100% financial and transactional consistency.

To explore the full implementation details, UI dashboards, and live operations screenshots, visit the dedicated project showcase:

12. References & Official Documentation

For deep dives into the open standards, messaging protocols, database primitives, and ERP APIs powering this architecture, consult the official engineering documentation and specifications:

RFID Standards & Streaming Bus

Distributed State & Cryptography

Enterprise ERP APIs

Observability & AI Agents

Table of Contents

Companion Project

Explore the operational control plane, live telemetry charts, and high-resolution architecture diagrams.

RFID to ERP Showcase
Félix Pupo Pérez
Félix Pupo Pérez
AI & Embedded Systems Architect

20+ years building industrial IoT telemetries, distributed cloud backends, and autonomous agentic pipelines.

About Félix