A car-history app looks simple until two data sources disagree. One workshop reports a brake service at 62,000 kilometers. An inspection center records 61,500 kilometers a week later. Another provider sends the same service record twice, using slightly different timestamps.
If the application merely sorts those rows by date, the result may look convincing while quietly misleading the reader. The hard part is not drawing the timeline. It is designing a trustworthy event pipeline behind it.
In this tutorial, we'll build a small Python prototype for receiving vehicle maintenance events, normalizing them, detecting duplicates, and surfacing inconsistencies without pretending that the software knows which source is correct.
Start with events, not a single vehicle record
A typical early design stores one mutable object per vehicle:
{
"vehicle_id": "demo-42",
"last_service": "2026-10-02",
"odometer_km": 62000
}
This is convenient for a dashboard, but it loses the questions that matter: Who provided the reading? When did the service actually happen? When did the system receive it? Was an earlier reading overwritten?
Instead, represent each observation as an event. A derived vehicle summary can still exist, but the source events remain available for inspection.
{
"event_id": "workshop-A:invoice-781",
"vehicle_id": "demo-42",
"event_type": "service",
"occurred_at": "2026-10-02T09:30:00+03:30",
"received_at": "2026-10-03T08:15:00Z",
"odometer_km": 62000,
"source": "workshop-A"
}
The two timestamps serve different purposes. occurred_at describes the claimed real-world event. received_at describes when the application learned about it. Keeping both makes delayed imports and backdated corrections easier to investigate.
Define a small, explicit validation boundary
The following code uses only Python's standard library. It intentionally handles a narrow event schema rather than trying to anticipate every workshop, insurer, or inspection system.
from datetime import datetime, timezone
ALLOWED_TYPES = {"service", "inspection", "repair", "odometer"}
def to_utc(value: str) -> datetime:
parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
if parsed.tzinfo is None:
raise ValueError("Timestamp must include a UTC offset")
return parsed.astimezone(timezone.utc)
def normalize_event(raw: dict) -> dict:
required = {
"event_id", "vehicle_id", "event_type", "occurred_at",
"received_at", "odometer_km", "source"
}
missing = required - raw.keys()
if missing:
raise ValueError(f"Missing fields: {sorted(missing)}")
if raw["event_type"] not in ALLOWED_TYPES: raise ValueError("Unknown event type") if not all(isinstance(raw[key], str) and raw[key].strip() for key in ("event_id", "vehicle_id", "source")): raise ValueError("Identifiers and source must be nonempty strings") reading = raw["odometer_km"] if reading is not None and (type(reading) is not int or reading < 0): raise ValueError("odometer_km must be a nonnegative integer or null") return { "event_id": raw["event_id"], "vehicle_id": raw["vehicle_id"], "event_type": raw["event_type"], "occurred_at": to_utc(raw["occurred_at"]), "received_at": to_utc(raw["received_at"]), "odometer_km": reading, "source": raw["source"], } Requiring an explicit time-zone offset avoids treating a local wall-clock time as if it were already UTC. Requiring an integer odometer reading also prevents ambiguous text such as "about 62k" from entering calculations unnoticed. That original text may still be useful, but it belongs in a separate raw-data record.
For a production system, schema evolution, access controls, a durable event store, and country-specific vehicle identifiers would need separate decisions.
Make repeated deliveries safe
Imports are retried. Webhooks are delivered more than once. A user can upload the same file twice. These are ordinary operational events, not exceptional failures.
An event_id should therefore identify a source event consistently. A database can enforce uniqueness on a combination such as (source, event_id). In a small prototype, we can illustrate the rule with a set:
seen = set()
accepted = []
def receive(raw: dict) -> str:
event = normalize_event(raw)
key = (event["source"], event["event_id"])
if key in seen:
return "duplicate"
seen.add(key)
accepted.append(event)
return "accepted"
The uniqueness check and insertion must be atomic in a real database. Otherwise, two workers could simultaneously accept the same event. A repeated identifier with changed content also deserves investigation rather than a silent overwrite; retain the raw payload or a content fingerprint for comparison.
Flag impossible-looking sequences without rewriting history
Suppose the sorted readings for one vehicle are 48,000 km, 62,000 km, and then 61,500 km. A consumer-facing interface should not silently replace the last number with 62,000. Nor should it automatically label the lower reading fraudulent. A transcription error, replaced instrument cluster, or source-matching mistake may explain it.
The safer behavior is to create a review flag:
def odometer_flags(events: list[dict]) -> list[dict]:
readings = sorted(
(e for e in events if e["odometer_km"] is not None),
key=lambda e: (e["occurred_at"], e["event_id"]),
)
flags = []
for previous, current in zip(readings, readings[1:]):
if current["odometer_km"] < previous["odometer_km"]:
flags.append({
"type": "reading_decreased",
"previous_event": previous["event_id"],
"current_event": current["event_id"],
})
return flags
This is a consistency check, not a fraud detector. For a multi-source feed, two readings may even describe different points within the same day, with uncertain event times. A production pipeline should preserve that uncertainty instead of manufacturing precision.
Other useful flags include unusually large jumps over short periods, a received timestamp far earlier than the claimed occurrence, repeated invoices with different identifiers, and mismatched vehicle identifiers. Each flag needs a documented interpretation and an escalation path.
Keep provenance visible in the API
An API returning only a polished timeline hides the very information readers might need to assess it. Consider returning the event and its context together:
{
"vehicle_id": "demo-42",
"events": [
{
"event_id": "workshop-A:invoice-781",
"event_type": "service",
"odometer_km": 62000,
"source": "workshop-A",
"status": "reported"
}
],
"review_flags": ["reading_decreased"]
}
A status such as reported means the application received a claim. It does not mean the claim was independently verified. If verification is performed, record who verified it, by which process, and when. Do not collapse these states into an unexplained green checkmark.
For broader Persian-language discussion of vehicles, automotive technology, and the car ecosystem, Automadar provides an automotive-focused publication. The engineering lesson here is narrower: a maintenance timeline earns trust by showing where its records came from.
Privacy is part of the data model
Vehicle history can reveal more than a repair. Timestamps and workshop locations may expose movement patterns; owner contact details may be included in imported documents. Decide what the timeline actually needs before ingesting entire invoices.
Separate identifiers used for matching from personally identifiable information. Avoid displaying raw workshop notes to other users. Define retention and correction workflows, and require authorization before exposing detailed vehicle records. If the application supports users in multiple jurisdictions, review the relevant privacy and consumer-disclosure requirements rather than assuming a single policy fits every market.
Test the failure modes, not just the happy path
Before releasing even a prototype, verify these cases:
- The same (source, event_id) arrives twice.
- Two sources reuse the same event ID for unrelated events.
- A timestamp has no time-zone offset.
- odometer_km is negative, a string, or a Boolean value.
- A late-arriving event belongs chronologically between two existing events.
- A corrected reading conflicts with a previously published summary.
- A vehicle identifier is missing or maps to more than one record. Tests should assert not only that bad data is rejected or flagged but also that no valid historical event is silently lost. The larger design lesson A vehicle-history interface is a projection of an evidence trail. Good dashboards are useful, but they cannot restore provenance that was discarded upstream. Capture claims as immutable events, keep arrival time separate from occurrence time, prevent accidental duplication, and present anomalies as reviewable facts rather than automatic verdicts.
The result is a modest system that is easier to audit, correct, and extend—exactly the properties a real automotive data product needs.
Disclosure: This tutorial was prepared with AI assistance. Its prototype code illustrates data-validation principles and is not a production-ready vehicle-history system.
