Streaming Every Bag: The Full AWS Architecture for Real-Time Airline Baggage Tracking, with Kafka and AI
DEV Community

Streaming Every Bag: The Full AWS Architecture for Real-Time Airline Baggage Tracking, with Kafka and AI

Disclosure: I wrote this article with AI assistance (Claude) for drafting, figures and simulation code. I designed the architecture and the study, and I reviewed and checked the facts, numbers and code. Originally published on Medium.

A transfer bag lands at 14:05. Its connection leaves at 14:50. The scanner on Pier C loses Wi-Fi for six minutes, and the backend never hears that the bag arrived.

This is the full AWS architecture that keeps every scan, from airport edge to standby Region, and the three places where AI on top of the stream helps people save the bag.

A new series: real-time airline operations on AWS. Same format as my Meridian Motors series on agentic AI for automotive supply chain, with a new fictional company: Cobalt Air, an airline with one busy transfer hub.

Level 300 ยท Solution architecture ยท Industry: travel and transportation ยท Services: AWS IoT Greengrass, AWS IoT Core, Amazon MSK, MSK Connect, MSK Replicator, Amazon Managed Service for Apache Flink, AWS Lambda, Amazon DynamoDB, Amazon SageMaker AI, Amazon Bedrock, AWS Step Functions, Amazon API Gateway, Amazon Cognito, Amazon SNS, Amazon S3, AWS Glue, Amazon Athena, Amazon QuickSight, Amazon Timestream for InfluxDB, AWS KMS, AWS Secrets Manager, Amazon CloudWatch, AWS CloudTrail

TL;DR

Most baggage systems still connect scanners, sorters and loaders to a central backend through synchronous calls. When the network to a pier drops, or a weather disruption triples traffic, scans are lost, and so is the location of the bag.

I designed the full AWS architecture for Cobalt Air, a fictional airline, and simulated 200 hub days to test it:

  • An edge-buffered Kafka backbone. AWS IoT Greengrass keeps messages on disk during outages; AWS IoT Core forwards them to Amazon MSK, keyed by bag tag. Lost scans per day fell from a median 2.6% (6.0% on bad days) to zero. The cost: on 77 of 200 days, bursts became consumer lag, up to 19 minutes in the worst case.
  • Edge vision that detects but never identifies. Person and bag tracks, no faces. A person-aware alert rule cut false unattended-bag alarms from 39.7 to 1.3 per camera-hour and still caught all 1,444 real cases.
  • Misconnect-risk ranking. A SageMaker model on the stream ranks transfer bags by savable risk for the hot-bag team. Misconnects fell from 10.8 to 8.0 per 1,000 transfer bags against the usual connection-time rule, 26% fewer, and the model won on all 200 days.
  • An Amazon Bedrock assistant drafts the paperwork for each exception, and a Step Functions workflow waits for a person to approve it.

All data is synthetic.

The business challenge

Airlines have improved: SITA's 2026 baggage report puts 2025 at 4.9 mishandled bags per 1,000 passengers. But transfers still cause 39% of mishandled bags, and each one costs an airline about $260.

IATA Resolution 753 asks airlines to track every bag at four points: acceptance, loading, transfer and arrival. Recording those scans is the easy part. The hard part is acting while there is still time. If a transfer bag's arrival scan reaches the backend 20 minutes late, the runner who could have carried it across the ramp never gets the call.

That is where synchronous integration fails. Each scanner calls the backend and waits. If the pier's network drops, the scanner retries for a minute and gives up. If a disruption sends rebooked bags through faster than the backend can answer, requests time out. The two worst moments for the network are the two moments operations most need the data.

Business outcomes Across 200 simulated hub days, each with its own traffic, outages and disruption:

Figure 1. Business outcomes across 200 simulated hub days (synthetic data, fictional airline)

Solution overview: the full AWS architecture

The streaming backbone follows an IBM framework for baggage tracking on AWS IoT and Amazon MSK that I worked on, published on the AWS Internet of Things Blog in 2024. Here I lay out every AWS service around it, make the design choices explicit, test them, and add the AI layer.

Figure 2. Full AWS architecture in seven layers, with a standby Region

The architecture has seven layers:

  • Airport edge. Scanners, RFID readers, sorters and belt loaders publish over MQTT to an AWS IoT Greengrass core at each station. Cameras feed a vision component on the same core; only anonymous track metadata leaves the airport.
  • Ingest. AWS IoT Core authenticates every device by certificate. An IoT rule writes each message to Kafka with the bag tag as the key.
  • Stream. A provisioned Amazon MSK cluster across three Availability Zones holds five topics and seven days of history.
  • Process and AI. Managed Service for Apache Flink keeps each bag's journey state and computes features. Lambda writes current state. A SageMaker endpoint scores misconnect risk. Amazon Bedrock drafts exception actions.
  • Serve and act. DynamoDB holds current bag state. API Gateway and Cognito serve a live board to staff. Step Functions runs approvals, and SNS pages security.
  • Analytics. MSK Connect archives every event to S3, catalogued by Glue and queried with Athena and QuickSight. Device telemetry goes to Timestream for InfluxDB.
  • Security and operations. KMS, IAM, Secrets Manager, CloudWatch and CloudTrail across every layer, plus a standby Region fed by MSK Replicator and DynamoDB global tables.

Figure 3. Every AWS service, its role and its key configuration

Where AI earns its place AI is not on the hot path for every scan. It sits in three places where data and decisions meet:

Figure 4. Where AI sits in the architecture, and why there

One transfer bag, end to end

Follow bag tag 0016 123456, arriving on an inbound flight with a 45-minute connection:

  • 14:05 - arrival scan. A ramp scanner publishes cobalt/DFW/bag/scan to the Greengrass core. The pier's uplink is down, so the disk spooler holds the message.
  • 14:11 - uplink returns. Greengrass forwards the spooled scan to AWS IoT Core over MQTT and TLS, in order.
  • 14:11 - into Kafka. The IoT rule writes it to bag.scan with key 0016123456. Every scan of this bag lands in the same partition, in order.
  • 14:11 - state and features. Lambda writes the bag's location to DynamoDB, but only if this scan is newer than the one stored. Flink updates the bag's journey and computes features: minutes available, terminal change, sorter load, any fault on its route.
  • 14:11 - risk. The SageMaker endpoint scores the bag. With 39 minutes left, a terminal change and a loaded sorter, it lands near the top of the bag.risk worklist.
  • 14:12 - a person acts. The hot-bag team sees the bag on the live board and sends a runner. If the bag misconnects anyway, Bedrock drafts the rush tag and the passenger message, and an agent approves them before Step Functions sends them to the airline's departure control and baggage reconciliation systems.

Part 1: The edge - AWS IoT Greengrass

Each station runs one Greengrass v2 core device, a small industrial PC in the bag room. It runs three things:

  • A local MQTT broker that every scanner, reader and sorter controller talks to. Devices never need the internet; they need the bag room's local network.
  • The MQTT bridge and disk spooler. The bridge relays local topics to AWS IoT Core. The disk spooler stores outbound messages on disk rather than in memory, so they survive an outage and a reboot.
  • The vision component. A detector and multi-object tracker, trained in SageMaker AI and packaged as a Greengrass component. Greengrass deployments roll out new model versions to every station, with rollback. Video never leaves the station. The component publishes a box and an anonymous track number for each person and bag, nothing more.

Part 2: Ingest and Kafka - topics, keys and the IoT rule

Figure 5. Kafka topic design on Amazon MSK

The single most important choice is the partition key. Kafka keeps order only within a partition. Keying bag.scan by bag tag puts every scan of one bag in one partition, so Flink sees each bag's journey in sequence. Order across bags does not matter. Bag tags spread evenly, so no partition runs hot.

The IoT rule sets that key. Two details matter. First, the Kafka rule action does not support MSK Serverless, which needs IAM authentication, so the cluster is provisioned. Second, the rule authenticates with SASL/SCRAM. MSK requires the SCRAM secret's name to start with AmazonMSK_ and to be encrypted with a customer-managed KMS key, not the default one.

{
  "sql": "SELECT *, topic(2) AS station FROM 'cobalt/+/bag/scan'",
  "actions": [
    {
      "kafka": {
        "destinationArn": "arn:aws:iot:us-east-1:111122223333:ruledestination/vpc/EXAMPLE",
        "topic": "bag.scan",
        "key": "${bagTag}",
        "clientProperties": {
          "bootstrap.servers": "b-1.cobalt-msk.example:9096,b-2.cobalt-msk.example:9096",
          "security.protocol": "SASL_SSL",
          "sasl.mechanism": "SCRAM-SHA-512",
          "sasl.scram.username": "${get_secret('AmazonMSK_cobalt_iot', 'SecretString', 'username', 'arn:aws:iam::111122223333:role/iot-msk-secret')}",
          "sasl.scram.password": "${get_secret('AmazonMSK_cobalt_iot', 'SecretString', 'password', 'arn:aws:iam::111122223333:role/iot-msk-secret')}",
          "acks": "all"
        }
      }
    }
  ]
}

The cluster turns on IAM access control as well. Flink, Lambda, MSK Connect and MSK Replicator all authenticate with IAM roles; only the IoT rule uses SCRAM.

One fact check I had to correct while building this: the Greengrass stream manager exports to Kinesis, S3 and IoT SiteWise, not to MSK. Edge buffering for this path is the disk spooler, and the hop into Kafka is the IoT rule.

Part 3: What the stream fixes, and what it costs

I simulated 200 hub days: 45,000 to 75,000 bags a day, five scans per bag, 40 gateways. Each day draws its own disruption burst (2 to 4 times normal load for 1 to 3 hours), its own gateway outages, at-least-once resends, and in half the days a regional failover. Both designs get the same processing capacity: three times the average load.

Figure 6. Left: share of scans lost per day. Right: the worst burst, where the synchronous design drops scans and the stream builds lag, then drains it

The synchronous design lost a median 2.6% of scans per day, and 6.0% on bad days. The stream lost none. About 2.4% of scans waited out an outage on a gateway's disk, for a median of 6 minutes, and then arrived.

But the burst did not disappear. On 77 of 200 days, consumers fell behind: a median peak of 4.5 minutes, and 19 minutes in the worst case. Kafka turns drops into lag, and lag is the number to watch.

Part 4: Late, repeated events, and effectively-once writes

Streaming creates two problems the old design did not have, because events now arrive late and sometimes twice.

Stale state. When a gateway flushes its buffer after an outage, an old scan can arrive after a newer one. A consumer that writes "latest arrival wins" showed a stale location for a median 0.85% of scans.

Duplicates. Edge resends, and the replay after a failover, delivered a median 0.67% of events twice. Kafka transactions give exactly-once processing inside Kafka, but a write to DynamoDB needs its own guard.

The answer is at-least-once delivery plus two conditions in one DynamoDB transaction: skip an event ID already seen, and accept a scan only if it is newer than the one stored.

import boto3
from botocore.exceptions import ClientError
ddb = boto3.client("dynamodb")
def apply_scan(ev):
  try:
    ddb.transact_write_items(
      TransactItems=[
        {
          "Put": {
            # idempotency: each event ID is written once
            "TableName": "processed_events",
            "Item": {"event_id": {"S": ev["event_id"]}},
            "ConditionExpression": "attribute_not_exists(event_id)"
          }
        },
        {
          "Update": {
            # versioning: only a newer scan moves the bag
            "TableName": "bag_state",
            "Key": {"bag_tag": {"S": ev["bag_tag"]}},
            "UpdateExpression": "SET loc = :loc, last_ts = :ts",
            "ConditionExpression": "attribute_not_exists(last_ts) OR last_ts < :ts",
            "ExpressionAttributeValues": {":loc": {"S": ev["location"]}, ":ts": {"N": str(ev["event_ts_ms"])}}
          }
        },
      ]
    )
  except ClientError as e:
    reasons = e.response.get("CancellationReasons", [])
    if e.response["Error"]["Code"] != "TransactionCanceledException" or any(r.get("Code") not in ("None", "ConditionalCheckFailed") for r in reasons):
      raise # throttling or a real error: let the consumer retry
    # otherwise a duplicate or an older scan: safe to skip

Give processed_events a TTL a little longer than the Kafka retention window, so it stays small. In production you would still record an older scan in the bag's journey history; the simulation only checks current state.

With both conditions, the same event streams produced no duplicates and no stale state.

Part 5: Edge vision - detect, don't identify

Unattended bags trigger a security response. A detector that flags every bag still for three minutes fires constantly, because travelers sit with their bags.

I rejected face recognition for linking bags to owners. It is biometric identification, with strict legal duties, and the EU AI Act prohibits real-time remote biometric identification in public spaces for law enforcement except in narrow cases.

Instead, the Greengrass vision component publishes anonymous tracks to vision.events, where a Flink job applies one of three rules:

  • A: alert when a bag has been still for three minutes.
  • B: link the bag to the nearest person when it stops; alert when that track is more than 10 m away, or lost, for three minutes.
  • C: as B, but treat the bag as attended whenever any person stays within 4 m for 10 of the last 15 seconds.

Figure 7. False unattended-bag alarms per camera-hour for three rules, 200 simulated camera-days. All three caught all 1,444 real cases

Rule A raised a median 39.7 false alarms per camera-hour. Rule B cut that to 10.6, but trackers lose and reassign IDs in crowds, and every lost owner track looked like an owner who had left. Rule C cut false alarms to 1.3 and still caught every real case, about three minutes after the owner walked away.

A rule C alert goes to SNS, which pages t

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.