Table of Contents

    Book an Appointment

    How Did We Discover the ClickHouse JSON vs Typed Columns Challenge?

    While working on a high-traffic SaaS platform for the hospitality and reservation industry, we were tasked with modernizing their event analytics pipeline. The system ingested approximately 6 million events per day, flowing from a Node.js ingestion layer through Apache Kafka and finally resting in ClickHouse for real-time dashboarding. The events represented 29 distinct user actions, such as search_submitted and booking_created.

    Each event shared a fixed set of core fields (timestamp, user_id, session_id), but also carried a highly variable properties object. For instance, a search event included city_id and result_count, while a booking event included restaurant_id and booking_date. Initially, treating these properties as a flat JSON string seemed like the most agile approach. However, as the business began relying heavily on real-time analytics to drive decisions, we realized this schema flexibility was silently degrading query performance.

    This architectural dilemma—deciding between rigidly flattening known properties into typed columns at ingestion versus relying on ClickHouse’s native JSON capabilities—is a common hurdle for medium-to-large-scale data pipelines. This challenge inspired the following deep dive, detailing how we tackled schema maintenance, query performance and the dreaded “promotion lag,” so other teams can avoid these costly architectural missteps.

    Why Do Dynamic Event Properties Create Bottlenecks in ClickHouse?

    ClickHouse is an exceptionally fast columnar database, meaning it thrives when data is strictly typed and stored in dedicated columns. When you store a dynamic payload as an untyped JSON string or a generic blob, you force the database engine to parse that string at query time. For a pipeline processing 6M events daily, executing JSONExtractString on millions of rows to filter or aggregate by restaurant_id leads to massive CPU spikes and unacceptable dashboard latency.

    From an engineering management perspective, fixing this usually requires one of two paths. Either you place the burden on the application layer to enforce schema (requiring backend engineers to constantly update ingestion code) or you place the burden on the database layer to handle dynamic types natively. For companies that choose to hire software developer teams to build their data infrastructure, getting this boundary right is critical to maintaining a healthy, scalable codebase.

    What Went Wrong With Untyped JSON Analytics at Scale?

    The core issue surfaced during what we call “promotion lag.” Promotion lag occurs when a previously insignificant property inside the JSON payload suddenly becomes critical for business reporting, but it hasn’t yet been promoted to a primary, indexed or typed column.

    During a major marketing campaign, the product team urgently needed real-time aggregations based on a promo_code field embedded deep within the booking_created event properties. Because the Node.js ingestion service was entirely agnostic to the contents of the properties object, it just passed the payload to Kafka. ClickHouse received it as raw JSON. Analysts wrote queries extracting the promo code on the fly. The result? Queries that previously took 40 milliseconds suddenly took 15 seconds, maxing out server threads and causing timeouts across the reporting UI.

    We needed a robust solution that eliminated promotion lag without requiring an application redeployment every time a new field became important.

    How Did We Evaluate ClickHouse JSON Parsing vs Column Flattening?

    To resolve the bottleneck, we mapped out the data flow and tested several architectural approaches. The goal was to balance ingestion simplicity with read-heavy performance requirements.

    Did We Consider Manual Flattening in Node.js?

    Our first thought was to update the Node.js ingestion service to inspect the incoming payload and flatten known-important properties into strictly typed columns before pushing to Kafka. We would maintain a schema registry of the 29 event types.

    While this would guarantee ClickHouse received perfectly structured columnar data, the maintenance overhead was massive. Every time a new property was added by the frontend team, the data engineering team would have to update the mapping logic, alter the ClickHouse schema and deploy. This tight coupling slows down delivery. It is a common anti-pattern we see when modernizing legacy systems, often prompting clients to hire dotnet developers for enterprise modernization to untangle such tightly coupled monolithic architectures.

    Did We Evaluate the Stringified JSON Approach?

    We briefly looked at keeping the payload as a string and using ClickHouse materialized columns (e.g., ALTER TABLE events ADD COLUMN promo_code String ALIAS JSONExtractString(properties, ‘promo_code’)). However, relying heavily on aliases and query-time extraction for highly queried fields still incurs parsing overhead, especially when filtering involves millions of rows.

    Did We Test ClickHouse Native JSON Type With Hints?

    ClickHouse introduced the experimental Object(‘json’) type (and subsequent native JSON inference improvements), which dynamically creates hidden subcolumns for JSON paths. This looked incredibly promising. It offered the agility of JSON with the performance of columnar storage. However, we found that relying entirely on dynamic inference for 29 distinct event types with rapidly changing structures sometimes led to edge-case type conflicts (e.g., a field sent as an integer in one event and a string in another), causing ingestion errors from Kafka.

    How Did We Implement the Hybrid ClickHouse Schema Architecture?

    Ultimately, we implemented a hybrid architecture utilizing ClickHouse Materialized Views (MVs) to handle the transformation natively within the database layer, completely decoupling it from the Node.js ingestion service.

    Here is how we structured the solution:

    • Ingestion Agility: The Node.js service remains dumb. It validates the core fields (timestamp, event_type, user_id) and passes the properties object as a String to Kafka.
    • Kafka Engine Table: ClickHouse reads from Kafka using a Kafka Engine table, ingesting the raw payload.
    • Core MergeTree Table: We defined our main analytics table with typed columns for the universally critical fields and a properties_json column for the rest.
    • Materialized Views for Promotion: We utilized Materialized Views to perform ETL upon insertion.

    To solve the “promotion lag” when a new field like promo_code became important, we didn’t touch Node.js. Instead, we altered the target table to add the column and updated the MV to extract it upon insertion.

    -- 1. The target Analytics Table
    CREATE TABLE event_analytics (
        event_time DateTime,
        event_type String,
        user_id UUID,
        -- Core promoted fields
        city_id Nullable(UInt32),
        restaurant_id Nullable(UInt32),
        promo_code Nullable(String),
        -- The fallback raw properties
        properties String
    ) ENGINE = MergeTree()
    PARTITION BY toYYYYMM(event_time)
    ORDER BY (event_type, event_time, user_id);
    -- 2. The Materialized View parsing the Kafka stream
    CREATE MATERIALIZED VIEW event_analytics_mv 
    TO event_analytics AS
    SELECT
        event_time,
        event_type,
        user_id,
        -- Promote specific fields to typed columns at write-time
        CAST(JSONExtractRaw(properties, 'city_id') AS Nullable(UInt32)) AS city_id,
        CAST(JSONExtractRaw(properties, 'restaurant_id') AS Nullable(UInt32)) AS restaurant_id
        JSONExtractString(properties, 'promo_code') AS promo_code,
        properties
    FROM kafka_events_stream;
    

    By extracting these values at write-time using the Materialized View, the data is stored in native columnar format. Querying promo_code now scans a dedicated String column rather than parsing JSON blobs, returning results in milliseconds instead of seconds.

    What Are the Key Architectural Lessons for Engineering Teams?

    Through resolving this architectural challenge, we extracted several key principles that apply to high-scale data pipelines:

    • Decouple Ingestion from Analytics Schema: Your application services (like Node.js or Python APIs) should not be tightly coupled to your data warehouse schema. If you are building extensive data pipelines, it is often wise to hire python developers for scalable data systems who understand how to build resilient, schema-agnostic ingestion layers.
    • Beware of Query-Time Parsing: While modern databases offer powerful JSON functions, query-time extraction will always lose to columnar reads at scale. Extract heavy-read fields at write-time.
    • Use Materialized Views for Agility: ClickHouse Materialized Views act as internal ETL pipelines. They allow you to promote fields dynamically without requiring cross-team coordination or backend redeployments.
    • Embrace the Hybrid Approach: Not every property needs to be a column. Reserve typed columns for fields actively used in filtering, grouping or joining. Leave unstructured metadata in a generic JSON or Map field.
    • Plan for Ecosystem Scalability: Downstream consumers of this data—whether they are BI tools, AI models or mobile platforms—depend on predictable performance. As your system grows, you might hire ai developers for production deployment to build recommendation engines on top of this data or hire app developer to create a mobile app that serves these insights. The underlying database architecture must be fast enough to support these integrations.

    How Can You Optimize Your ClickHouse Data Pipelines?

    Choosing between manual column flattening and native JSON in ClickHouse isn’t a binary decision; it’s a spectrum of optimization. For medium-to-large event pipelines (like our 6M events/day scenario), the most robust solution is to ingest raw flexible data and use database-native features like Materialized Views to enforce strict typing on the fields that actually matter to your queries. This eliminates “promotion lag,” keeps backend application logic simple and guarantees lightning-fast analytics.

    If your organization is struggling with data pipeline bottlenecks, scaling analytics architecture or modernizing legacy systems, contact us to learn how our pre-vetted dedicated engineering teams can help you build high-performance data platforms.

    Social Hashtags

    #ClickHouse #DataEngineering #RealTimeAnalytics #EventAnalytics #QueryOptimization #BigData #ApacheKafka #DataArchitecture #MaterializedViews #DatabasePerformance #DataPipelines #SoftwareEngineering #SaaS #BackendDevelopment #OLAP

    Frequently Asked Questions

    Trusted by businesses building and scaling software products.

    Since 1999

    3,500+ Projects Delivered

    US Based Accountability

    Selected clients across our delivery history