Zero Labs
Industry News / AI

Building a Production Crowdsourced Data Platform From Scratch

Source · Towards AI By Bassem Essameldin Omar

From the publisher’s feed, collected in the ZeroLabs newsroom.

Over a few months, I built a crowdsourced data platform from scratch. An 8-Phase Journey through Kubernetes, Kafka, Spark, Airflow, dbt, and Observability on GCP. While working on those phases, I learned much about data concepts and how they are applied in a real-world platform.Photo by JD X on UnsplashWhat this project isThis is a from-scratch clone of a crowdsourced production data engineering stack on GCP, built to learn the real architecture by actually running it: Kafka ingestion, a Spark medallion lake, Airflow orchestration, dbt transformations, a Looker Studio dashboard, Terraform-managed infrastructure, GitHub Actions CI/CD, and full Prometheus/Grafana/Alertmanager observability.A simulator emits fake measurements for 100 mobile devices, representing measurements collected from crowd devices in different locations to build analytical solutions. Those measurements flow through a FastAPI ingest service into Kafka, land in GCS via a sink connector, get progressively refined through a bronze/silver/gold Spark pipeline into BigQuery, get reshaped into analytics-ready marts by dbt, and surface in a Looker Studio dashboard. Airflow orchestrates the whole thing hourly, and Prometheus-based alerting monitors it. In addition, we developed startup/teardown bash scripts to build the required infrastructure between sessions and destroy running resources to control GCP billing costs.The Project DiagramThis blog is aimed at data engineers and data scientists who want to know when the real data pipeline actually broke, why, and how we found out. Every phase below includes at least one real debugging story. Several of them took multiple sessions to crack, and two in particular are genuinely instructive about how subtle a wrong assumption can be when the evidence superficially seems to confirm it.Phases 00–01: Terraform foundations and GKE AutopilotEverything starts from a layered Terraform setup, split into modules with different lifecycles: foundations (VPC, NAT, IAM, Workload Identity Federation, service accounts) is long-lived and applied once; gke (the cluster itself, Workload Identity bindings) is ephemeral and recreated every session; lake and cloudsql sit in between, but separate from the compute layer.The cluster is GKE Autopilot, which trades node management for a set of real constraints you don’t hit on a standard GKE cluster. Each group of Kubernetes pods is isolated in a namespace. Workload Identity is the other piece worth calling out: every pod that needs GCP access (Kafka Connect reading a GCS credential, Spark writing to BigQuery, Airflow workers submitting SparkApplications, dbt reading/writing BigQuery) runs as a Kubernetes ServiceAccount bound to a GCP service account via Workload Identity, never a mounted key file. For example, the same Workload Identity Federation setup lets GitHub Actions authenticate to GCP with zero stored secrets; No service-account JSON key sitting in a GitHub Secret anywhere.Phase 02: Kafka, ingest, and a GCS sink connectorKafka runs via Strimzi in KRaft mode (no ZooKeeper), fronted by a FastAPI ingest service that validates incoming measurements with Pydantic and serializes them to Avro via a Schema Registry before publishing. A GCS Sink Connector then lands the raw Avro files in a landing bucket.The Kafka Connect image itself is a small, instructive lesson in its own right: it’s confluentinc/cp-kafka-connect:7.6.0 plus exactly one layer. confluent-hub install confluentinc/kafka-connect-gcs:10.0.7, but the Dockerfile that built it was never committed anywhere. Months later, reconstructing it required pulling the live image and running docker history; no-trunc against it to recover the exact base image and install command. Lesson for any team running ad-hoc image builds: if the Dockerfile isn’t in version control, the image itself eventually becomes the only source of truth for how it was built, with the image still sitting in a registry.The real debugging story here is the sink connector’s `path.format` configuration. It’s a Joda-Time pattern string (year=YYYY/month=MM/day=dd/hour=HH), and Joda-Time treats every bare letter as a pattern symbol, including the literal characters in words like “year” and “month” themselves. Left unquoted, this throws Illegal pattern component: r at the exact moment the connector’s task tries to start. Critically, this failure happens at the task level, not the connector level. A GET /connectors//status call shows the connector itself as RUNNING while its one task sits FAILED, silently. The parent object looks healthy while the actual unit of work underneath it is broken — turned out to be a recurring shape across this whole project, not a one-off. The fix is to quote every literal character: ‘year’=YYYY/’month’=MM/’day’=dd/’hour’=HH.Phase 03: Spark and Data LakeThree Spark jobs implement the classic bronze/silver/gold pattern: bronze_job.py reads raw Avro from landing and writes partitioned Parquet; silver_job.py deduplicates and enriches H3 geohash; gold_job.py aggregates into hourly operator-level metrics and loads them into BigQuery.The one design choice worth flagging to anyone building something similar: every one of these three jobs does a full mode(“overwrite”) of its entire output on every single run. There’s no incremental or delta processing anywhere in this pipeline. bronze_job.py reads everything currently sitting in landing each time it runs, not just what’s new since the last run; gold_job.py truncates and reloads the whole BigQuery table, not just the current hour’s partition.This has a real, concrete operational consequence worth internalizing: a successful job run tells you nothing about data freshness. Early in this project, a bq query returning real-looking rows was mistaken for confirmation that the pipeline was working end-to-end, but it was Spark successfully re-aggregating three-day-old backlog data that had accumulated in landing while a downstream connector was silently broken. The only reliable freshness check is inspecting the actual date values inside the output, not the job’s exit code.Phase 04: AirflowAirflow 2.9.2 runs on KubernetesExecutor, backed by Cloud SQL Postgres, with DAGs synced live from the repo via GitSync. The daily_batch_pipeline DAG chains delete_old_jobs → bronze_job → silver_job → gold_job → dbt_transform, each Spark task submitting a SparkApplication and polling for completion.The defining bug of this phase: a real triggered DAG run had bronze_job fail in well under a second, every single time, while airflow tasks test daily_batch_pipeline bronze_job run manually succeeded fully, submitting and polling a SparkApplication to completion. The difference was invisible until traced carefully: tasks test executes in-process inside the scheduler pod, which runs as the airflow-scheduler ServiceAccount. A real KubernetesExecutor task runs in a separate worker pod, launched with kubernetes_executor.worker_service_account_name, which in this project’s config was a different ServiceAccount (ksa-airflow). The RBAC ClusterRoleBinding granting sparkapplications CRD permissions had only ever been bound to airflow-scheduler — meaning every real task attempt hit an instant 403 Forbidden, while the manual test (running as the already-privileged scheduler identity) worked perfectly and told us nothing was wrong.The general principle: when a manual, in-process reproduction of a task succeeds, but the real scheduled execution fails identically and instantly, suspect an identity mismatch between the two execution contexts before anything else. A task's test success proves the code is correct, not that the deployment’s permissions are.Phase 05: Data transformation (dbt)The dbt project follows a conventional staging/marts split. stg_operator_metrics is a thin view over the raw gold table; daily_operator_summary and operator_rankings are tables built on top of it; bi_operator_daily is a fourth model. A combined view joining the daily summary and the rankings, built specifically so Looker Studio would have one clean source rather than needing to blend two tables in its own UI.The column names year, month, day, hour in the source table read like strings, and the staging model’s first version wrote LPAD(month, 2, ‘0’), which failed immediately with No matching signature for function LPAD: Argument types: INT64, INT64, STRING. The columns were genuinely INT64 in BigQuery, despite looking exactly like the kind of zero-padded string column that naming convention would suggest. The fix was a trivial CAST(month AS STRING) before padding, but it’s a reminder that a column’s name and its apparent values from a cursory SELECT * are not a substitute for checking INFORMATION_SCHEMA or the table’s actual DDL.The operational gotcha worth flagging for anyone running dbt inside Kubernetes rather than a managed dbt Cloud environment: the dbt project is containerized, and the container image is not kept in sync by GitSync. Airflow’s DAG files update live, within about 60 seconds of a push, because GitSync polls the repo directly into the scheduler’s pod. The dbt image does not. A model change requires an explicit Docker build and docker push before the next DAG run will reflect it, something that’s easy to forget once you’re used to everything else in the stack updating itself.Phase 06: Looker StudioThe BI layer is deliberately simple: Looker Studio’s native BigQuery connector pointed directly at bi_operator_daily, authenticated via the viewer’s own Google account: no service-account key, no credential file, nothing to rotate. The dashboard focuses on trends over time: download/upload speed and latency as time-series charts broken down by operator, with a date-range control and an operator filter.Looker Studio dashboard for download/upload speedsWorth noting for anyone costing this out: Looker Studio itself is free, including the native BigQuery connector. The only real cost surface is the BigQuery query volume the connector generates on each view/refresh. The cost is negligible here given the table’s size, but worth checking data-source freshness settings on larger projects, since more frequent refreshing means more repeated queries against the same underlying data.Phase 07: CI/CD PipelineThree GitHub Actions workflows, all authenticated through the Workload Identity Federation pool from Phase 00. No stored service-account keys anywhere in GitHub Secrets. docker-build.yml detects which application changed (ingest-api, simulator, spark, dbt) and rebuilds only that image, tagged with both: latest and the commit SHA. terraform-plan.yml runs fmt/validate/plan per module on every push, read-only. terraform-apply.yml is workflow_dispatch-only — applying real infrastructure changes stays a deliberate, manual action, never automatic.The most instructive failure here: a terraform plan run in CI simply hung for 50 minutes with no output, eventually needing to be cancelled. A required Terraform variable with no default value and no TF_VAR_* environment variable supplying it. Locally, Terraform prompts you interactively for a missing value. On a GitHub Actions runner, there’s no stdin to answer that prompt, so Terraform just sits there, indefinitely, until the job’s hard timeout eventually kills it hours later. Any CI pipeline running Terraform needs -input=false as a baseline default. It converts a silent, multi-hour hang into an immediate, readable error the moment a required value is missing, which is a dramatically better failure mode even though it changes nothing about whether the underlying problem exists.A second, related lesson: cancelling that hung run left an orphaned state lock in the GCS backend (Error acquiring the state lock… conditionNotMet), because killing a CI job mid-flight doesn’t give Terraform a chance to release a lock it had already acquired before getting stuck. terraform force-unlock resolved it, but the general rule is worth stating plainly: any Terraform run that gets killed rather than finishing naturally should be assumed to have left a stale lock behind, and the next attempt should check for that before doing anything else.Phase 08: observability using Prometheus and GrafanaThe monitoring stack layers three new metric sources onto the existing Prometheus/Grafana/Alertmanager install from Phase 01: a PodMonitor scraping Kafka’s already-configured JMX exporter on the broker pods; a hand-added JMX exporter on Kafka Connect (which, running as a plain Deployment rather than a Strimzi-managed CRD, had no metrics pipeline at all until this phase); and Airflow’s built-in StatsD exporter, customized with extraMappings to turn its dag/task-ID-embedded metric names into real Prometheus labels.Grafana DashboardOn top of the metrics, three PrometheusRules cover Kafka Connect task failure, sustained consumer lag, and Airflow task failure, routed to Slack via Alertmanager, but scoped specifically to alerts carrying a project: data-pipeline label, after an early version that changed the default route accidentally sent every one of the chart’s generic built-in cluster-health alerts (KubeMemoryOvercommit, KubePodNotReady) to the same channel.Alrets landed a Slack channelConclusionEight phases, a genuine production-shaped stack, and a working pipeline carrying real (simulated) data from ingestion to a dashboard, with alerting watching over it, built the only way that actually teaches the architecture, which is by running it against a live cluster and letting it break in realistic ways rather than reading about how it’s supposed to work.The full project, including every Terraform module, Kubernetes manifest, Spark job, dbt model, and GitHub Actions workflow referenced above, lives in the project’s repository, with a README covering setup and session-lifecycle details for anyone who wants to run it themselves.GitHub Repository:https://github.com/bassemessam1/crowdsource-data-app-cloneBuilding a Production Crowdsourced Data Platform From Scratch was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.