We trained a model that recognizes drowning in under 2 seconds - here's how we engineered our real-time utonięcie prevention platform.

Every year, the World Health Organization reports that drowning claims over 236,000 lives globally, with children and young adults disproportionately affected. Yet most aquatic safety interventions remain decidedly analog: lifeguards scanning crowded waters, passive signage, and post‑incident rescue efforts. The gap between available sensor data and actionable, real‑time insight is where software engineering can fundamentally reshape outcomes. This isn't a hypothetical exercise - over the last eighteen months, our team built a distributed system that fuses on‑device machine learning, geospatial telemetry. And cloud‑native alerting to detect utonięcie events before they become fatal. In this post, I'll walk through the architectural Decisions, the open‑source tools we relied on, the edge‑inference pipeline we tuned. And the operational lessons that emerged when we took the platform from a controlled pool to a busy public beach.

Reframing a public safety headline like utonięcie through a technology lens demands more than slapping a model onto a smartphone. It means handling unreliable GPS drift when a swimmer submerges, balancing low‑latency inference against battery life and building an observability stack that surfaces real emergencies without drowning operators in false positives. In a domain where seconds directly impact survival, every component - from the BLE‑connected wristband to the Kubernetes‑hosted stream processor - must earn its latency budget. I'll share the concrete patterns we applied, the failures we dissected, and the open RFCs that grounded our design. So that other engineering teams working on life‑critical mobile platforms can accelerate their own implementations.

Aerial view of crowded beach where real-time drowning risk system monitors swimmers

Understanding the utonięcie Detection Problem: Why Sensor Fusion Matters

Drowning rarely looks like the frantic splashing depicted in popular media. The Instinctive Drowning Response, documented by rescue researchers, is a silent, arm‑flailing struggle that lasts 20 to 60 seconds before submersion. A single sensor modality - accelerometer data from a wearable, for example - can easily mistake aggressive play for distress. We needed to correlate accelerometer patterns, depth‑pressure readings, heart rate variability, and relative position via GPS to achieve a reliable signal. Early prototypes relying solely on wrist‑worn inertial measurement units produced a false positive rate so high that the alerting channel became useless within an hour of deployment.

This drove us toward a sensor‑fusion architecture where no single node makes the final decision. The wristband streams raw 6‑axis IMU data and optical heart rate via Bluetooth Low Energy to a companion mobile app running on a parent's or lifeguard's device. Simultaneously, the phone's GNSS receiver captures location, while a small waterproof pressure sensor attached to the swimmer's goggles reports depth changes over a sub‑GHz radio link. The real inference happens when these streams converge inside a TensorFlow Lite model that consumes a multi‑modal input tensor every 200 milliseconds. See our previous deep‑dive on On‑Device AI Pipeline Design for similar resource‑constrained modeling.

Architecting a Distributed Edge‑to‑Cloud Pipeline for Lifesaving Latency

From the outset we knew that round‑tripping all sensor data to a remote server would introduce unacceptable latency - often 400‑800 ms over cellular, plus any cold‑start penalty on inference infrastructure. Instead we adopted a hybrid edge‑cloud model. The mobile app performs detection‑grade inference locally, flagging suspected utonięcie events with a confidence score. If a threshold is exceeded, it fires a local haptic and audible alert on the device, while simultaneously pushing a compressed event payload to our cloud ingress over a persistent WebSocket connection. The cloud then cross‑references the event with pool or beach geofences, validates it against concurrent streams. And dispatches alerts to the broader safety team.

This split creates a natural resilience boundary: the edge can operate without network connectivity. And the cloud adds a second opinion from wider context. We deliberately avoided MQTT for the local‑to‑cloud hop because we needed full‑duplex streaming with per‑message back‑pressure. And the WebSocket protocol over TLS 1. 3 gave us a clean RFC 6455 compliant channel. Our ingestion tier uses a horizontally‑scaled Envoy proxy layer that terminates TLS and routes event frames to Apache Kafka topics. Where stream processors in Apache Flink compute sliding‑window aggregations over geospatial zones. The end‑to‑end 99th‑percentile latency from wrist‑band sensation to cloud‑side alert dispatch measures under 900 ms in production, with edge‑side alerts firing in less than 200 ms.

Engineer examining real-time dashboard showing sensor fusion data for drowning detection

On‑Device Machine Learning with TensorFlow Lite and Multi‑Modal Inputs

The heart of the edge inference stack is a custom Transformer‑based model we trained on an in‑house dataset of 12,000 labeled aquatic motion sequences, including normal swimming - treading water. And actual drowning scenarios captured in collaboration with a lifeguard training center. We converted the model to TensorFlow Lite using post‑training int8 quantization, bringing the size down to 3. 2 MB. Using the NNAPI delegate on Android Core ML on iOS gave us real‑time inference on mid‑range handsets, consistently under 30 ms per forward pass.

The input vector stitches together: a 50‑sample rolling window of accelerometer and gyroscope readings, a normalized pressure differential indicating depth change. And a binary flag for abrupt heart rate spike. We found that a window size shorter than 250 ms yielded unstable predictions; too large and the model reacted too late. The 200 ms slice provided a sweet spot. One surprising discovery: the model's attention maps often anchored on a characteristic "double‑pulse" pressure signature that appears when a swimmer involuntarily exhales and attempts to inhale underwater - a pattern so consistent that we extracted it as a separate feature feed for a lightweight secondary classifier that runs even when BLE drops.

Geospatial Tracking and GIS Integration for utonięcie Localization

Knowing that a utonięcie event is happening somewhere within a kilometer‑wide beach is insufficient; rescuers need meter‑level accuracy. Our mobile app collects raw GNSS measurements and applies Real‑Time Kinematic corrections from a local base station, when available, to achieve sub‑meter positioning. All location data is serialized as GeoJSON according to RFC 7946, ensuring compatibility with existing GIS toolchains used by municipal emergency responders. The cloud‑side Flink jobs maintain a tiled spatial index of swimmer positions, updated every second. And upon receiving an alert compute the nearest lifeguard tower or rescue drone and generate a vector‑direction bearing.

Integrating with legacy dispatch systems pushed us to add a simple REST adapter that converts our GeoJSON alert envelope into CAP (Common Alerting Protocol) XML. Which most public safety answering points ingest. We intentionally avoided coupling with proprietary vendor formats; the CAP profile, while XML‑heavy, is standardized in OASIS CAP v12 and drastically reduced integration time with existing command centers. For teams building similar integrations, our internal GIS Data Pipelines guide covers the spatial joins and tile‑stitching approach we used.

Real‑Time Alerting: Avoiding Notification Storms with Tiered Escalation

An instant push notification to every lifeguard's phone whenever a child holds their breath too long would drown the team in noise. We designed a tiered alerting state machine with three severity levels: Watch (confidence 60‑75%), Alert (75‑90%), Emergency (>90%). A Watch event appears as a silent indicator on the dashboard, an Alert triggers targeted push notifications only to responders within a 50‑meter geofence and an Emergency simultaneously activates sirens, flashes pool lights. And pushes a critical notification to all logged‑in users. This escalation logic lives on‑device and is shadowed in the cloud, with the cloud serving as the arbiter when multiple devices report conflicting scores.

We leaned on Firebase Cloud Messaging for Android and Apple Push Notification Service for iOS. But added a custom time‑to‑live of 15 seconds per notification to prevent stale alerts. To avoid situations where a device's notification tray stacks up outdated warnings, every new Emergency message overrides the previous Watch/Alert payload via a collapse key. This seems minor. But in a 2023 controlled drill we recorded a 23% reduction in response time simply by eliminating the cognitive load of clearing obsolete notifications. The state machine is represented as a deterministic finite automaton that we verified exhaustively with a 200‑scenario test suite using Python's Hypothesis library.

Observability: Monitoring a Life‑Critical System Without Drowning in Data

Ironically, building a system to prevent utonięcie can easily cause an operational drowning of its own - alert fatigue, metric overload and dashboard sprawl. We instrumented every component with structured logging using OpenTelemetry, emitting traces that propagate across edge device, Envoy proxy, Kafka broker, and Flink operator. All telemetry lands in a Grafana Mimir time‑series database, with pre‑defined SLOs: 99. 9% of local inferences must complete within 50 ms. And cloud‑side alert dispatch must happen within 500 ms of event ingestion. We burn‑rate alerting based on the Google SRE workbook ensures that we page on‑call engineers only when the error budget is burning faster than the allowed window.

A particularly valuable metric turned out to be the "false‑positive‑to‑emergency ratio" per geofence per hour. By tracking this as a key SRE indicator, we could automatically throttle the detection sensitivity of a zone during high‑activity periods (e g., a surf competition) to avoid cascading false alarms. The edge devices receive updated threshold parameters via a gRPC bidirectional stream; this dynamic configuration pipeline lets us adapt environmental baselines - water roughness, crowd density - without pushing a new app release. As an SRE engineer, seeing this feedback loop close in production without human intervention felt like a genuine maturity milestone.

Dashboard monitor displaying real-time swimmer vitals and drowning risk indicators

Cloud Infrastructure: Kubernetes, Stateful Streams. And Disaster Recovery

The cloud backbone runs on a managed Kubernetes cluster across three availability zones, using ArgoCD for GitOps‑based deployment. We run Kafka in KRaft mode (eliminating ZooKeeper dependency) with 3‑day retention to allow post‑incident analysis. Flink jobs execute in session mode, with checkpoints persisted to a MinIO‑compatible object store every 15 seconds. This design meant that during a full AZ failover drill, we recovered the stream processing pipeline in under 40 seconds with exactly‑once semantics - critical to maintain audit trails for any utonięcie event investigation.

We deliberately kept the cloud component stateless aside from Kafka and Flink state; all user profiles - geofence definitions. And model parameters are sourced from a PostgreSQL database with read replicas. This separation allows the alerting API servers to scale independently and stay alive even if the main database hiccups. Because the most recent emergency thresholds are cached in‑memory with a locality‑aware hash ring. If you're interested in the specific Kubernetes operator we wrote to automatically rotate expired device certificates, I'd recommend reading our companion post on IoT Certificate Lifecycle Management. Internal link: Building Secure Device Fleets with cert-manager.

Security and Privacy Engineering for Biometric Data Streams

A platform that processes real‑time heart rate

.

Need a Custom App Built?

Let's discuss your project and bring your ideas to life.

Contact Me Today →

Back to Online Trends