AI System DesignData and Feature InfrastructureModule 12 — Advanced data architecture

Designing Sensor Data Quality Services That Distinguish Missing Readings from Zero

Question 43 of 47 · Updated

On this page

Treat zero as a measured value and missing as a quality state. Build a streaming quality service that knows which readings are expected, validates received samples against device-specific contracts, detects missing slots, and publishes both the measurement and its quality metadata. Downstream AI models should receive only eligible observations or explicitly approved imputations—not silent zero replacements.

How would you design a sensor-data quality service that distinguishes missing readings from genuine zero-valued measurements?

*ASD-094 · Module 12 — Advanced data architecture · Learning order 30.*

1. Start with a real problem#

A factory predicts pump failures using a flow sensor that reports every 10 seconds. A stopped pump legitimately produces zero flow. A disconnected sensor produces no reading. If both become zero in the feature store, the model cannot distinguish a stopped machine from an unavailable sensor.

Incoming evidenceQuality stateNumeric value
Healthy sensor reports 0 L/minOBSERVED0
No sample before arrival deadlinePENDINGNone
Expected sample overdueMISSINGNone
Packet contains null, undocumented encoding or error sentinelINVALIDNone
Sensor reports 0 but calibration is invalidINVALIDNone
Valid sample arrives after deadlineOBSERVED, late flagActual value
Reading replaced by approved estimateIMPUTEDEstimated value

The central rule: absence is never evidence of a physical zero. Even a received zero needs validation. A stuck-at-zero sensor can produce apparently valid packets while malfunctioning.

This is an operational sensor-quality problem, not just missing-value preprocessing. Existing ML lessons cover imputation and missingness indicators; the MLOps upstream-delay lesson covers dataset readiness. ASD-009 covers shared ingestion and ASD-092 covers conflicting numerical facts. Here the service establishes whether each expected measurement exists and is usable.

2. Architecture#

Loading diagram…

The device registry defines each stream's unit, valid range, sampling schedule, source firmware, calibration status and allowed delay. The processor validates incoming events and tracks expected slots. It stores original evidence separately from the quality projection. A feature assembler enforces the model's input contract; it does not decide independently that missing means zero.

Start with a broker, keyed streaming workers, a durable state store and an observation archive. Add a separate time-series database only if query needs justify it.

3. Design the measurement contract#

A normalized observation needs:

FieldPurpose
Tenant, device, channel, boot/session IDIdentify the actual stream; handle counter resets
Sequence number and expected slotDetect duplicate samples and gaps
Event time and received timeDistinguish delayed delivery from old measurements
Value, unit and schema versionPreserve numeric meaning
Quality status and reason codesDistinguish missing, invalid and observed
Calibration and health evidenceEstablish whether a reading can be trusted
Revision and source referenceSupport correction and historical reconstruction

Use a nullable numeric value with an explicit status. Do not use a numeric sentinel such as -999 internally. Decode documented vendor sentinels before unit conversion; a value that is legitimate in one measurement domain may be a sentinel in another. If legacy firmware uses zero for both sensor failure and measured zero without a separate diagnostic flag, the ambiguity cannot be resolved reliably from that payload alone. Upgrade the device protocol or mark those observations uncertain.

Heartbeats and measurements are separate. A gateway heartbeat confirms connectivity, not measurement correctness. A healthy heartbeat with absent samples suggests a sensor/channel or acquisition failure; missing both suggests a wider communication or power issue. Neither proves the root cause. Detect calibration expiry, diagnostic errors, out-of-range readings and suspicious flatlines. A flatline is a reason for investigation, not automatic evidence of failure: a stationary machine can legitimately report zero repeatedly.

4. Detect missing readings in event time#

For a periodic sensor, create expected slots from its approved schedule and active operating interval. Key state by tenant, device, channel and source incarnation. Use a documented matching tolerance so one reading is assigned to at most one slot.

Suppose readings are due at 10:00:00, 10:00:10 and 10:00:20, with five seconds of arrival grace. If the 10:00:10 reading has not arrived by 10:00:15, publish a missing disposition. Before the deadline it is pending. A sequence gap is an early signal, not proof of permanent loss; packets can arrive out of order. Heartbeat and timer processing must still work when a stream is silent.

Loading diagram…

Every transition after an emitted result creates a new revision; it does not erase the old state. Track event-time watermarks for window progress, but do not assume a watermark proves all events arrived. Use a processing-time deadline for operational alerting, with explicit event-time alignment and allowed-lateness policy. Device clock skew, reboot and scheduled maintenance need their own handling. For event-triggered sensors without a periodic sampling promise, silence may be normal; do not invent expected slots.

Store occurrence identity and compare conflicting duplicate payloads. Deduplicate retransmissions before counting samples. Checkpoint expected-slot state, timers and source positions; make output revisions idempotent. A worker restart should not generate duplicate missing records. Late data should update the affected window and dependent features, preserving the original as-known revision.

5. Worked example: missing data changes the prediction#

A one-minute window expects six flow readings. At closure the observations are:

Slot (seconds)Reading (L/min)State
010Observed
100Observed
20—Missing
3020Observed
40—Invalid
5010Observed

Four valid observations sum to 40. Their observed-sample mean is 10 L/min, with coverage 4/6 = 66.7%. Filling both unavailable slots with zero produces 6.67 L/min, which falsely suggests lower flow. Neither observed-sample mean nor zero-filled mean necessarily represents the true full-window average.

Publish the observed mean, valid/expected count, missing and invalid counts, and window revision. If the model requires at least five valid slots, hold this feature or use the approved fallback. If a valid 15 L/min reading later arrives for slot 20, the corrected observed mean becomes 55/5 = 11 L/min, coverage 83.3%. Publish a successor revision. A prediction originally made with 66.7% coverage retains its original evidence.

6. Small tested implementation#

This deliberately narrow function shows the critical boundary: never use a truthiness check such as if not value to identify missing data.

PYTHON
from math import isfinite def classify(received, value, healthy, now, due): """One expected sample slot; inputs already scoped and deduplicated.""" if not received: return ('PENDING' if now < due else 'MISSING', None) if (not healthy or type(value) not in (int, float) or not isfinite(value) or not 0 <= value <= 100): return 'INVALID', None return 'OBSERVED', value assert classify(True, 0, True, 9, 10) == ('OBSERVED', 0) assert classify(True, 12, True, 11, 10) == ('OBSERVED', 12) assert classify(False, None, True, 9, 10) == ('PENDING', None) assert classify(False, None, True, 10, 10) == ('MISSING', None) assert classify(True, None, True, 10, 10) == ('INVALID', None) assert classify(True, 0, False, 10, 10) == ('INVALID', None) assert classify(True, -999, True, 10, 10) == ('INVALID', None) assert classify(True, float('nan'), True, 10, 10) == ('INVALID', None) assert classify(True, float('inf'), True, 10, 10) == ('INVALID', None) assert classify(True, False, True, 10, 10) == ('INVALID', None) assert classify(True, 101, True, 10, 10) == ('INVALID', None) assert classify(True, 100, True, 10, 10) == ('OBSERVED', 100) print('12 checks passed')

Executed locally with Python 3.13.5: 12 checks passed. The 0–100 range is fictional; real devices require their own schema, units and calibration rules. The function assumes an authenticated, deduplicated sample has already been assigned to one expected slot and that health is trusted. It does not schedule timers, distinguish detailed error reasons, validate actual sensors or implement persistent corrections. Late status is tracked separately by the surrounding service. The exact code MD5, excluding the terminal newline, is 65bcea09bab152df681718d038865ebb.

7. Decide how AI models consume quality states#

SituationPractical policy
Valid zeroPass zero unchanged
Brief gap in a slowly varying signalAllow bounded forward-fill only if validated; preserve age and imputed flag
Long outageUse a separately evaluated degraded model or abstain
Invalid calibration or safety-critical measurementHold affected use until eligible evidence exists
Offline historical correctionRebuild a new feature revision; preserve as-known history

Imputation is an estimate, never a recovered measurement. Forward-fill during a rapidly changing process may conceal a genuine fault. Linear interpolation using a later observation is not eligible for a real-time prediction made before that observation arrived. Fit learned imputation on training data only. Expose missingness, age and coverage to models that were trained and tested for those inputs. Validate model performance during actual outage patterns, not only random artificial masking. Safety controls remain separate from predictive models.

8. Scale and operate the service#

For an illustrative fleet of 100,000 devices reporting every 10 seconds, expected throughput is 10,000 samples/s. At 200 bytes per normalized event, logical input is 2 MB/s or 172.8 GB/day before compression, indexes and replication. Partition by scoped device/channel, batch writes and use bounded active-slot state and checkpointed timers rather than scanning all historical readings. Keep raw history and revisioned summaries under approved retention. If the broker stalls, distinguish fleet-wide ingestion failure from individual sensor outages and avoid flooding operators with one alert per missing slot.

Monitor valid zero rate, expected-slot coverage, missing/invalid/late rates, sequence gaps, heartbeat age, calibration status, duplicate conflicts, correction lag and prediction fallback rates by device type and site. A sudden jump in zeros after a firmware release is worth investigating even if packet delivery remains healthy. Correlate alerts by gateway and release, protect tenant-scoped evidence and limit high-cardinality telemetry.

Test duplicate and out-of-order packets, device restart, clock skew, legitimate zero periods, stuck-at-zero faults, null/sentinel payloads, timer recovery, scheduled downtime, late corrections and model admission. Independently compare against known physical measurements. A passing software check cannot establish that a physical sensor is calibrated.

Interview-ready answer#

I would define a device-specific measurement and arrival contract, keep a nullable value separate from its quality state, and validate zero just like any other received value. A keyed stream processor would track expected slots, heartbeats, sequences and calibration, emit explicit missing states at deadlines and publish revisioned corrections for late readings. The feature store would preserve coverage, age and imputation metadata; models would use only approved input profiles, degrade or abstain when necessary. I would monitor both device and ingestion health and test genuine zeros, failures and recovery independently.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython