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

> Source: <https://dev.to/vijay_gokarn_4bedefa60dad/streaming-every-bag-the-full-aws-architecture-for-real-time-airline-baggage-tracking-with-kafka-5b7o>
> Published: 2026-12-06 05:03:47+00:00

**Recommendation:** Buffer edge telemetry locally with a disk spooler and partition the stream by entity key so scans survive network drops and stay ordered per bag.
More in the playbook "Running AI in production": <https://wpnews.pro/playbooks/production-ops>

*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](https://medium.com/@vijay.v.gokarn/streaming-every-bag-the-full-aws-architecture-for-real-time-airline-baggage-tracking-with-kafka-f7b0c1e9932e).*

*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**

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 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.

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.

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)*

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:

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

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*

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

`cobalt/DFW/bag/scan` to the Greengrass core. The pier's uplink is down, so the disk spooler holds the message.`bag.scan` with key `0016123456`. Every scan of this bag lands in the same partition, in order.`bag.risk` worklist.
Each station runs one Greengrass v2 core device, a small industrial PC in the bag room. It runs three things:

Video never leaves the station. The component publishes a box and an anonymous track number for each person and bag, nothing more.

*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.

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.**

Streaming creates two problems the old design did not have, because events now arrive late and sometimes 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.

``` python
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.

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:

*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 the security team.

The lesson surprised me: **tracker errors, not detector errors, drive the false alarms.** A rule that tolerates identity switches mattered more than a better model.

A hot-bag team can hand-carry only so many tight transfers an hour. The usual rule flags bags under minimum connection time (45 minutes, 60 with a terminal change) and works them soonest first.

The stream knows more. Flink computes features as events arrive: when the first transfer scan arrived, whether the bag changes terminals, how loaded the sorters are, and whether a belt on its route has reported a fault. A gradient-boosted classifier on a SageMaker real-time endpoint scores each bag, and the result goes to `bag.risk`. The key design choice: rank by **risk times savability**, not risk alone. A bag with five minutes left is high risk and lost anyway; the runner's time is better spent on one with 25.

*Figure 8. Misconnects per 1,000 transfer bags: no action, connection-time rule, and model ranking (left); rule against model per simulated day (right)*

With a team of 6 to 15 bags an hour, misconnects fell from 16.6 per 1,000 transfer bags with no action, to 10.8 with the rule, to 8.0 with the model. Both rankers separate risky from safe bags about equally well (AUC 0.97 against 0.95). The gain comes from spending scarce runner time on bags that are both at risk and still savable.

Every misconnect, missing scan or unattended bag starts paperwork: a rush tag, a mishandled-bag report, a message to the passenger. An assistant on Amazon Bedrock reads `ops.alerts` and the bag's journey from DynamoDB and drafts each one, with Bedrock Guardrails on input and output.

It only drafts. The draft starts a Step Functions execution that pauses on a task token. The agent sees the draft on the live board, served through API Gateway and signed in with Cognito. Only when the agent approves does the board return the token, and only then does the workflow call the airline's departure control and baggage reconciliation systems. Approval is enforced by the workflow, not by the prompt. Scan payloads and free-text notes are parsed into fixed fields and never treated as instructions. **AI ranks and drafts; people act.**

I have not measured this component. It is the part that most needs a pilot with real baggage agents.

`min.insync.replicas` of 2 and `acks=all`. Losing one broker or one zone loses no data.` bag_state` replicated automatically.
MSK publishes consumer-lag metrics to CloudWatch, including `EstimatedMaxTimeLag`, the estimated seconds to drain the lag. I alarm on it per consumer group: warn at 2 minutes and page at 5 for the risk pipeline, because minutes are what a runner loses. Time lag is derived from offset lag, so a consumer that stops completely can look fine; pair it with an alarm on `MaxOffsetLag` growing while nothing is consumed. Add the Greengrass spooler's backlog age per station, Flink checkpoint duration, and SageMaker endpoint latency.

A big hub's scan volume is small for Kafka: 75,000 bags times five scans is under 400,000 events a day, a few events a second on average and a few dozen at the peak. Throughput does not set the partition count. Consumer parallelism does: a consumer group can use at most one consumer per partition, and partitions are hard to add later without moving keys. I would start `bag.scan` with enough partitions for the largest consumer fleet you expect in a disruption, on a small three-broker cluster.

*Figure 9. Failure modes, guards and tests*

*Figure 10. Validation summary across randomized simulations*

Every experiment uses fixed random seeds, randomizes its parameters across 200 worlds, and compares each AI component with the rule it would replace, not with doing nothing. The code reproduces every chart in a few minutes on a laptop.

The limits are real. All data is synthetic. The latency model ignores broker and network delay. The vision experiment simulates detector and tracker outputs rather than running a model on video. The misconnect model trains and tests on data from the same generator, which flatters it. The runner times and capacities are assumptions. Each piece needs validation on an airline's own scan history and footage, under its privacy review.

If you are explaining this design to a team, or in an interview, these are the points I would draw:

Real-time baggage tracking is an IoT problem first: events from thousands of devices on shaky networks must arrive, in order, effectively once. On AWS that means Greengrass at the edge, IoT Core and a keyed Kafka log on MSK in the middle, and idempotent, versioned writes at the end, with lag, ordering and duplicates designed for from day one. Once every event is on the stream, AI earns its place in three spots: anonymous edge vision that quiets false alarms, risk ranking that puts runners on bags they can save, and an assistant that drafts the paperwork for a person to approve.

If you work on IoT, streaming or airline operations, I would like to hear what you are building. Leave a comment or connect with me on LinkedIn.

**Vijay Gokarn** is a Senior AWS Solutions Architect at IBM Consulting, based in the Dallas area. He designs event-streaming, data and generative-AI platforms on AWS for airline, automotive and financial-services operations, and has worked at IBM since 2012 as a developer, BPM specialist, JavaScript lead and cloud architect. He holds an M.S. in computer science from Portland State University and an AWS certification, and writes about real-world AWS architecture at [vijay-gokarn.com](https://vijay-gokarn.com).

Cobalt Air, its hub and all data in this article are fictional. The views are my own and not those of any employer or client.
