Skip to content
Vibhrav Jha.Let’s talk
All projectsDistributed Systems

Distributed Weather Data System

Weather queries through a tested node failure

My contributionCassandra data modeling, gRPC service implementation and failure testing within the course project.

FieldDistributed Systems / Data Engineering

View repository

Academic project

Architecture diagram of NOAA data, a Cassandra cluster and a query service

The work
behind the interface.

Kept writes available during the tested loss of one Cassandra node, with read-consistency fallback in a three-node NOAA weather-data service.

  • Python
  • Cassandra
  • gRPC
  • Protobuf
  • Spark
  • Docker

The result

Writes continued during the recorded single-node-loss test. Reads could fall back from two replicas to one.

The problem

Implemented a gRPC service over a three-node Cassandra cluster for NOAA time-series data.

A decision worth examining

Model partition and clustering keys around weather queries, with read-consistency fallback when replicas become unavailable.

Read the README.

View original README
READMEArchitecture, setup and usage

Distributed Weather Data System with Cassandra

A fault-tolerant weather data ingestion and analysis system built on Apache Cassandra. Features configurable consistency levels for read/write availability tradeoffs, automatic failover mechanisms, and real-time temperature analytics from NOAA weather stations across Wisconsin.

Overview

This system processes weather data from the National Oceanic and Atmospheric Administration (NOAA), storing temperature readings from weather stations in a distributed Cassandra cluster. It demonstrates advanced distributed database concepts including tunable consistency, prepared statements, and graceful degradation under node failures.

Architecture

System Architecture

The system consists of:

  • Cassandra Cluster (3 nodes): Distributed database with 3x replication
  • gRPC Server: API layer with Spark integration for data preprocessing
  • Weather Clients: Data ingestion and query interfaces

Key Features

🗄️ Distributed Data Model

  • Partitioning: Data organized by station ID for efficient queries
  • Clustering: Time-series ordering by date within partitions
  • Static Columns: Station metadata stored once per partition
  • User-Defined Types: Custom types for temperature records

⚖️ Tunable Consistency

  • Strong Consistency: R + W > RF guarantees (R=2, W=1, RF=3)
  • High Availability: Automatic fallback to relaxed consistency (R=1)
  • Write Optimization: Always accept sensor data when any replica available
  • Read Profiles: Dual-mode reads with automatic degradation

🛡️ Fault Tolerance

  • Automatic Failover: Graceful degradation on node failures
  • Error Handling: Clear "unavailable" messages when quorum lost
  • Data Durability: 3x replication across cluster nodes
  • Prepared Statements: Optimized queries with configurable consistency

🚀 Spark Integration

  • Data Preprocessing: Parse and transform station metadata
  • Bulk Loading: Efficient batch inserts into Cassandra
  • Text Processing: Extract structured data from fixed-width files

Technical Stack

  • Database: Apache Cassandra 5.0+
  • Data Processing: Apache Spark (local mode)
  • RPC Framework: gRPC, Protocol Buffers
  • Backend: Python 3.x
  • Client Connector: cassandra-driver
  • Containerization: Docker, Docker Compose

Data Model

Schema Design

CREATE KEYSPACE weather WITH replication = {
  'class': 'SimpleStrategy',
  'replication_factor': 3
};

CREATE TYPE weather.station_record (
  tmin int,  -- tenths of degrees Celsius
  tmax int   -- tenths of degrees Celsius
);

CREATE TABLE weather.stations (
  id text,                    -- Partition key: Station ID
  date date,                  -- Clustering key: Measurement date
  name text static,           -- Static: Station name
  record station_record,      -- UDT: Temperature readings
  PRIMARY KEY (id, date)
) WITH CLUSTERING ORDER BY (date ASC);

Design Rationale:

  • Partition Key (id): Groups all data for a station together
  • Clustering Key (date): Enables efficient time-range queries
  • Static Column (name): Avoids redundant storage across dates
  • UDT (station_record): Bundles related temperature fields

API Operations

1. Schema Inspection

python3 ClientStationSchema.py

Returns the Cassandra table definition with all configuration details.

2. Station Lookup

python3 ClientStationName.py USW00014837

Output: MADISON DANE CO RGNL AP

Retrieves station name using partition key query.

3. Temperature Recording

python3 ClientRecordTemps.py

Ingests weather data from Parquet files into Cassandra with W=1 consistency.

Sample Output:

Inserted USW00014837 on 2022-01-01 with tmin=-99 and tmax=-32
Inserted USW00014837 on 2022-01-02 with tmin=-166 and tmax=-82
...

4. Maximum Temperature Query

python3 ClientStationMax.py USR0000WDDG

Output: 344 (34.4°C)

Returns the highest temperature ever recorded at a station.

Consistency Guarantees

Write Profile (RecordTemps)

  • Consistency Level: ONE (W=1)
  • Rationale: Maximize availability for sensor uploads
  • Behavior: Accepts writes when any single replica reachable
  • Use Case: Sensors with limited storage can't afford write failures

Read Profile #1: Strong (StationMax)

  • Consistency Level: TWO (R=2)
  • Guarantee: R + W > RF ensures no stale reads
  • Behavior: Requires quorum of replicas
  • Fallback: Automatically switches to Available profile on failure

Read Profile #2: Available (StationMax)

  • Consistency Level: ONE (R=1)
  • Guarantee: Best-effort availability
  • Behavior: Returns data from any single replica
  • Tradeoff: May return slightly stale data during conflicts

Fault Tolerance Demonstration

Scenario: Single Node Failure

Initial State - All nodes healthy:

$ docker exec p6-db-1 nodetool status
UN  172.27.0.4  70.28 KiB  16  64.1%  rack1
UN  172.27.0.3  70.26 KiB  16  65.9%  rack1
UN  172.27.0.2  70.28 KiB  16  70.0%  rack1

Failure Injection:

docker kill p6-db-2

After Failure:

$ docker exec p6-db-1 nodetool status
UN  172.27.0.4  70.28 KiB  16  64.1%  rack1
DN  172.27.0.3  70.26 KiB  16  65.9%  rack1  # DOWN
UN  172.27.0.2  70.28 KiB  16  70.0%  rack1

System Behavior

Writes (W=1): ✅ Continue normally

$ python3 ClientRecordTemps.py
Inserted USW00014837 on 2022-01-01 with tmin=-99 and tmax=-32
# Success - at least one replica available

Reads - Strong (R=2): ⚠️ Cannot achieve quorum

  • Primary profile fails (requires 2 of 3 replicas)
  • Automatically falls back to Available profile

Reads - Available (R=1): ✅ Continue with fallback

$ python3 ClientStationMax.py USR0000WDDG
344 (fallback_to_available)
# Success using degraded consistency

Implementation Highlights

Prepared Statements

Prepared once in __init__, used many times:

class StationService:
    def __init__(self):
        # Strong consistency read
        self.max_query_strong = self.session.prepare(
            "SELECT MAX(record.tmax) FROM weather.stations WHERE id = ?"
        )
        self.max_query_strong.consistency_level = ConsistencyLevel.TWO
        
        # Available fallback read
        self.max_query_available = self.session.prepare(
            "SELECT MAX(record.tmax) FROM weather.stations WHERE id = ?"
        )
        self.max_query_available.consistency_level = ConsistencyLevel.ONE
        
        # High-availability write
        self.insert_temp = self.session.prepare(
            "INSERT INTO weather.stations (id, date, record) VALUES (?, ?, ?)"
        )
        self.insert_temp.consistency_level = ConsistencyLevel.ONE

Automatic Failover Logic

def StationMax(self, request, context):
    try:
        # Try strong consistency first
        result = self.session.execute(
            self.max_query_strong, 
            [request.station]
        )
        return StationMaxReply(tmax=result[0].max_tmax, error="")
        
    except (Unavailable, NoHostAvailable):
        # Fall back to available profile
        try:
            result = self.session.execute(
                self.max_query_available, 
                [request.station]
            )
            return StationMaxReply(
                tmax=result[0].max_tmax, 
                error="fallback_to_available"
            )
        except (Unavailable, NoHostAvailable):
            return StationMaxReply(tmax=0, error="unavailable")

Spark Data Loading

# Parse fixed-width station metadata file
stations_df = spark.read.text("ghcnd-stations.txt") \
    .selectExpr(
        "SUBSTRING(value, 1, 11) AS id",
        "SUBSTRING(value, 39, 2) AS state",
        "SUBSTRING(value, 42, 30) AS name"
    ) \
    .filter("state = 'WI'")

# Bulk insert into Cassandra
for row in stations_df.collect():
    session.execute(
        "INSERT INTO weather.stations (id, name) VALUES (?, ?)",
        [row.id.strip(), row.name.strip()]
    )

Data Sources

  • Station Metadata: NOAA GHCND stations file (fixed-width format)
  • Weather Readings: Parquet files with daily temperature observations
  • Coverage: Wisconsin weather stations (2022 data)
  • Temperature Scale: Tenths of degrees Celsius

Deployment

Build and Start Cluster

docker build -t weather-cassandra .
export PROJECT=weather
docker compose up -d

Wait for Cluster Ready

docker exec weather-db-1 nodetool status
# Wait until all nodes show UN (Up/Normal)

Generate gRPC Stubs

docker exec -w /src weather-db-1 sh -c \
  "python3 -m grpc_tools.protoc -I=. --python_out=. --grpc_python_out=. station.proto"

Start Server

docker exec -it -w /src weather-db-1 python3 server.py

Performance Characteristics

Read Latency by Consistency Level

ConsistencyHealthy Cluster1 Node Down2 Nodes Down
ONE (R=1)~2ms~2ms~2ms
TWO (R=2)~4ms~4msUNAVAILABLE
THREE (R=3)~6msUNAVAILABLEUNAVAILABLE

Write Availability

ConsistencyHealthy Cluster1 Node Down2 Nodes Down
ONE (W=1)100%100%100%
TWO (W=2)100%100%UNAVAILABLE

Skills Demonstrated

  • Distributed Databases: Cassandra architecture, replication strategies
  • Data Modeling: Partition keys, clustering keys, static columns, UDTs
  • Consistency Tuning: CAP theorem tradeoffs, quorum configuration
  • Fault Tolerance: Graceful degradation, automatic failover
  • RPC Communication: gRPC, Protocol Buffers
  • Data Processing: Apache Spark for ETL
  • Error Handling: Exception management, retry logic
  • Performance Optimization: Prepared statements, query tuning

Technologies

  • Apache Cassandra (distributed NoSQL)
  • Apache Spark (data preprocessing)
  • gRPC & Protocol Buffers (RPC framework)
  • Python 3.x (cassandra-driver, pyspark)
  • Docker & Docker Compose (orchestration)

A production-ready demonstration of distributed database design with tunable consistency and fault tolerance.

Distributed Property Lookup Service

  1. Aranyaka wildlife-image application interface

    Fullstack

    Aranyaka

  2. DermaNet hackathon prototype showing classification output and a generated explanation

    ML & AI

    DermaNet

  3. AI-generated concept illustration of source documents connected to retrieved evidence and an answer

    ML & AI

    Private-Data RAG

  4. Before It Breaks dashboard separating real weather from synthetic equipment telemetry and estimated costs

    ML & AI

    Before It Breaks

  5. Architecture diagram of simulated stock records flowing through Kafka to HDFS

    Distributed Systems

    Stock Streaming Engine

  6. Vyaya dashboard with clearly labeled synthetic demonstration data

    Fullstack

    Vyaya

  7. Study assistant interface with retrieved source context

    ML & AI

    Fine-Tuning vs. RAG

  8. Architecture diagram of NOAA data, a Cassandra cluster and a query service

    Distributed SystemsViewing

    Distributed Weather Data System

  9. Distributed Property Lookup Service project image

    Distributed Systems

    Distributed Property Lookup Service

  10. Architecture diagram connecting MySQL, a gRPC service and HDFS storage

    Distributed Systems

    HDFS & SQL Pipeline

  11. Architecture diagram of Spark processing, SQL and analysis

    Distributed Systems

    Spark Analytics

  12. Multi-Source ELT Pipeline project image

    Data Engineering

    Multi-Source ELT Pipeline

  13. Wisconsin schools in their geographic context — explanatory architecture diagram

    Data Engineering

    GCP Geospatial Pipeline

  14. Chinook Music Store SQL Analytics project image

    Data Engineering

    Chinook Music Store SQL Analytics

  15. Yelp Geospatial Analytics project image

    Data Engineering

    Yelp Geospatial Analytics

  16. E-Commerce Semantic Search Engine project image

    Data Engineering

    E-Commerce Semantic Search Engine

  17. Retail Sales Forecasting project image

    ML & AI

    Retail Sales Forecasting

  18. Making tool dependencies inspectable — explanatory architecture diagram

    ML & AI

    AI Agent Tool Dependency Graph

  19. From public records to operational questions — explanatory architecture diagram

    Data Engineering

    Palantir Foundry and AIP Build Challenge

  20. StudyFlow study-session dashboard

    Fullstack

    StudyFlow

  21. Habit Command Center planning dashboard

    Fullstack

    Habit Command Center

  22. Interfaces across web and mobile — explanatory architecture diagram

    Fullstack

    React Web & Mobile

  23. Startup Scout project image

    Fullstack

    Startup Scout

  24. Inventory-Based Recipe Planner project image

    Fullstack

    Inventory-Based Recipe Planner

  25. Concurrent Word Count and Performance Benchmarking project image

    Data Engineering

    Concurrent Word Count

  26. Data structures matched to their assumptions — explanatory architecture diagram

    Computing Foundations

    Algorithm Design

  27. Campus Navigator project image

    Fullstack

    Campus Navigator

  28. i-Songly: Song Management Engine project image

    Fullstack

    i-Songly

  29. An experiment that can resume — explanatory architecture diagram

    ML & AI

    CIFAR-100 with LeNet

  30. Fashion-MNIST Neural Network Classifier project image

    ML & AI

    Fashion-MNIST Classifier

  31. PCA Eigenfaces and Image Reconstruction project image

    ML & AI

    PCA Eigenfaces

  32. Two routes to the same regression objective — explanatory architecture diagram

    ML & AI

    Lake Mendota Ice Regression

  33. Bayesian Language Detection project image

    ML & AI

    Bayesian Language Detection

  34. Explanatory diagram of the video-fingerprint benchmark: 25 sources, 75 transformed variants and 1,875 comparisons.

    ML & AI

    Video-Fingerprint Benchmark

All projects