Migrating 1.3 Billion IoT Rows to ClickHouse Cloud
Dec 8, 2025 · Updated Oct 21, 2026 · 16 min read
How I migrated 1.3 billion IoT rows from SQL Server to ClickHouse Cloud and brought dashboard queries from 45 seconds to under 2 seconds.

An IoT analytics platform had outgrown SQL Server. Years of telemetry made historical analysis slow, and dashboard queries could take 45 seconds. I moved its analytical workload to ClickHouse Cloud while keeping the transactional workload in SQL Server.
We migrated 1.3 billion rows. Dashboard queries fell below 2 seconds, single-device time-series queries below 20 milliseconds, and bulk exports below 500 milliseconds. At cutover, the combined database bill was $2,200 lower per month.
This article covers the architecture and reusable techniques behind that migration.
When SQL Server Becomes the Bottleneck
The platform collects device telemetry for historical analysis and operational dashboards.
The workload combined a large append-only history, time-range aggregations, per-device lookups and related metadata. At cutover, it held more than 1.3 billion telemetry rows.
The SQL Server environment was struggling under the load—but the problems went deeper than just volume:
- 6 TB database storing years of telemetry and associated database overhead
- $4,000/month total RDS spend, including compute, storage and automated snapshots
- Aggregation queries competed with the transactional workload.
- Historical dashboards needed a different physical data layout.
The existing clustered-key layout did not match the analytical query patterns. Grouping data by device and time was a better fit for the reads we needed to serve.
Think of a library shelved by acquisition date instead of subject. A per-device query has to find related readings scattered among unrelated rows. Matching the physical sort order to common filters reduces that work.
Pre-computation helped some queries, but added storage and write costs. We needed a better fit for the analytical workload.
Why ClickHouse for IoT Telemetry
When evaluating time-series databases, we considered TimescaleDB, InfluxDB, and ClickHouse. Each has strengths, but our decision criteria narrowed the field quickly:
- Query performance: Sub-second aggregations over billions of rows
- Operational complexity: Managed service preferred over self-hosting
- Cost efficiency: Better price/performance than RDS SQL Server
- SQL compatibility: Team already knows SQL, minimize learning curve
- Ecosystem maturity: Production-ready tooling and documentation
- Developer experience: Quality of console, observability tooling, and debugging workflows
ClickHouse Cloud won on all counts—and the developer experience deserves special mention. The console is genuinely well-designed: an intelligent query editor with autocomplete, a visual analyzer showing exactly which parts are slow and why, real-time metrics dashboards, and documentation that doesn't assume you're already an expert. When you're debugging a slow query at 2am, tooling quality matters. ClickHouse Cloud feels like a product built by engineers who use it themselves.
Here's why it was the right fit for our IoT telemetry use case:
Columnar storage suits telemetry aggregations. A query that averages a numeric value over time can read the value and timestamp columns without reading every attribute of each event.
Compute and storage can scale separately. ClickHouse Cloud stores data in object storage and uses sparse primary indexes over sorted data. Analytical scans benefit from reading selected columns and pruning ranges through the sort key.
Compression benefits from repeated values and ordered data. In this comparison, the migrated analytical dataset occupied approximately 19 GB. The original 6 TB database included other forms of storage overhead, so this is a before-and-after footprint comparison rather than a codec-only benchmark.
Native time-series functions. Time bucketing and ASOF JOINs support aggregation and closest-preceding-time matching without moving the join into application code.
ClickHouse Cloud's managed offering eliminates operational overhead. The SharedMergeTree engine handles replication and distributed storage automatically. No manual sharding, no replica management, no 3am pages about disk space.
Before diving deeper, here are some ClickHouse-specific terms you'll encounter throughout this article:
- MergeTree: ClickHouse's primary table engine family, optimized for high-volume inserts and analytical queries. Think of it like a filing system where new documents go into an inbox, and a background worker periodically sorts and consolidates them into organized folders.
- ReplacingMergeTree: A MergeTree variant that deduplicates rows with the same primary key, keeping only the latest version. Think of a voicemail system that keeps only your most recent message from each caller—duplicates pile up temporarily, but during periodic cleanup, older messages from the same person get purged. Essential for IoT data where sensors occasionally retransmit readings.
- Materialized View: A view that physically stores its results and updates automatically when source data changes. Think of it as a live scoreboard that updates itself whenever the game state changes—you don't recalculate from play-by-play logs every time someone asks the score. Unlike SQL Server indexed views, ClickHouse MVs can transform data and write to separate target tables.
- ASOF JOIN: A time-series-aware join that matches each row to the closest preceding row in another table. Like checking your bank balance—you get the most recent statement before today's date, not the one from next week. Perfect for correlating sensor readings with the most recent forecast.
- Codec: A compression algorithm applied at the column level. ClickHouse supports Delta (for sequential values), ZSTD, LZ4, and others—often stacked for maximum compression.
Architecture Overview
Our data pipeline looks like this:
Swipe sideways to see the whole diagram.
- Devices → event gateway: telemetry arrives as events.
- Gateway → Lambda: an ingestion function processes the events.
- Lambda → ClickHouse Cloud: inserts use HTTPS.
The analytical design uses MergeTree-family tables, materialized views for pre-computation and dictionaries for reference lookups.
ReplacingMergeTree and duplicates: replacement happens during background merges. Choose the sorting key and version column to match the record identity and update semantics, and make query-time correctness explicit.
Migrating 1.3 Billion Rows Without Downtime
Database migrations at this scale require careful planning. A naive "stop writes, export, import, resume" approach would have meant hours of downtime—unacceptable for a real-time monitoring system. Here's how we did it.
Phase 1: Schema Design
The foundation of good performance in ClickHouse is schema design. We optimized for our query patterns: time-range filtering and aggregation by device.
Table structure decisions:
- Engine: a MergeTree-family table suited to the data’s insert and replacement semantics.
- Partitioning: a bounded time-based partition scheme that fits retention and maintenance.
- Order key: device and event time where those are the leading query filters.
- Codecs: choose compression from representative values and measured read costs.
Design the sort key around the filters the application actually uses.
Why these codec choices?
- Timestamps: ordered timestamps can benefit from delta encoding followed by compression.
- Integers: test integer codecs against the actual distribution.
- Strings: use dictionary encoding when values repeat enough to justify it.
- Numeric values: measure compression and query cost rather than copying another workload’s codec settings.
Related time-series tables may need more than one timestamp in their sort key. Distinguish the time an observation was recorded from the time it describes.
Phase 2: Dual-Write and Feature-Flagged Reads
Before touching historical data, we set up dual writes. New sensor readings went to both SQL Server and ClickHouse simultaneously—this let us validate ClickHouse on live production data before committing to the full migration.
The clever part was the read path. We implemented a feature flag that routed queries based on timestamp:
- Data after the cutover date → read from ClickHouse
- Data before the cutover date → fall back to SQL Server
This gave us a live A/B test. We could verify ClickHouse was returning correct results for recent data while SQL Server continued serving historical queries. No big-bang cutover risk.
Phase 3: Historical Data Migration
With dual writes proven stable, we backfilled historical data into ClickHouse. As each month's data landed, the feature flag's cutover date automatically expanded backward—gradually shifting more query traffic to ClickHouse without any manual intervention.
Export strategy:
- Custom export jobs that partitioned data by month for parallel processing
- Exported to Parquet format—columnar on both ends meant no schema translation headaches
- Parquet's built-in compression saved bandwidth during transfer
Load strategy:
- ClickHouse Cloud's native Parquet import handled the heavy lifting
- Parallel loads by partition kept throughput high
Validation:
- Row count comparisons between source and destination
- Spot-check queries on known aggregations to verify data integrity
Phase 4: Cutover
After validating data consistency, we flipped the switch:
- Dashboard migration: update the analytical read path.
- Canary: move a bounded share of traffic and compare correctness and latency.
- Cutover: move the remaining analytical traffic after validation.
- Rollback: retain the previous read path for the agreed rollback window.
Final validation:
- Spot-checked aggregation queries for numerical accuracy (match SQL Server results within rounding tolerance)
- Tested dashboard load times under concurrent user load
- Verified materialized views were populating correctly from live data
Enabling Features That Were Impossible in SQL Server
Materialized views let us move repeated analytical work from reads to inserts. The following patterns describe reusable capabilities, not the customer’s feature inventory.
Pattern 1: Closest-Preceding-Time Enrichment
An ASOF JOIN can match an event to the most recent reference observation for the same entity. That is useful when two streams report at different intervals.
For an illustrative timeline, an event at 14:37 matches the reference observation at 14:00 rather than the later observation at 15:00. The timestamps in the diagram demonstrate the join rule; they are not customer records.
Swipe sideways to see the whole diagram.
Pattern 2: Precomputed Associations
When an application repeatedly joins the same related records, precomputing the association can simplify its read path. Check late arrivals and corrections explicitly: an incremental materialized view responds to inserts into its source, not arbitrary later changes to every joined table.
Pattern 3: Latest Value Caching
A small derived table can keep the latest state per entity. With ReplacingMergeTree, background replacement is eventual, so a query that requires the latest state must resolve versions explicitly. Keep that query bounded to the entities it needs.
Pattern 4: Filtered Derived Tables
A derived table can retain only records relevant to a recurring query. Define that predicate from the application’s requirements.
The SQL Server Alternative (and why it failed)
| Feature | SQL Server Indexed Views | ClickHouse MVs |
|---|---|---|
| Storage overhead | 1:1 replication (doubles storage) | Incremental only |
| ASOF JOIN support | ❌ Not supported | ✅ Native |
| Complex WHERE clauses | ❌ Very limited | ✅ Full SQL |
| Update on INSERT | ⚠️ Performance hit on writes | ✅ Designed for high-throughput writes |
| Aggregate in view | ❌ Limited (no GROUP BY with joins) | ✅ Full support |
In this migration, indexed views increased the SQL Server storage footprint. A ClickHouse materialized view writes its selected result into a target; the target’s size depends on that transformation and still needs to be measured.
Pattern 5: Efficient Bulk Exports to S3
ClickHouse can export query results directly to object storage in Parquet format. Bound the export by a stable time interval, select the required columns and configure credentials outside the article.
Performance Optimization Deep-Dive
Good schema design got us 80% of the way there. The remaining 20% came from codec strategy and understanding how ClickHouse executes queries.
Codec Strategy and Compression
In this comparison, the analytical dataset occupied approximately 19 GB, compared with the original 6 TB SQL Server footprint. Those totals include different kinds of overhead and should not be read as a codec-only comparison.
Ordered timestamps and repeated numeric values compress well. Noisy measurements usually compress less. Test codecs on representative data and include query CPU cost in the decision.
Query Performance Patterns
ClickHouse excels at certain query patterns. Understanding them is key to fast queries.
Pattern 1: Bounded time-range filtering
Use explicit interval bounds so partition and primary-index pruning can discard irrelevant ranges.
Pattern 2: Per-device time-series queries
Filter on the leading sort-key columns and request only the values needed. The migrated system’s single-device queries returned in under 20 milliseconds.
Pattern 3: Precomputed enrichment
Querying a derived table can avoid repeating the same join on every dashboard read. That shifts work to ingestion, where memory, correctness and late-arrival behavior still need attention.
Connection Management from Lambda
Lambda execution environments can reuse a client across warm invocations. Keep configuration in the runtime environment rather than publishing an endpoint or account-specific defaults.
Choose batching, acknowledgement and retry behavior together. Those choices depend on workload shape and the supported ClickHouse version.
The Numbers: Before and After
Here's the side-by-side comparison:
| Metric | SQL Server | ClickHouse Cloud | Improvement |
|---|---|---|---|
| Time-series query (single device, 7 days) | Several seconds | <20ms | 100x+ |
| Bulk data export (100s of MBs) | Timeout or very slow | <500ms (network-bound) | Network is the bottleneck, not DB |
| Latest-state dashboard | 12s | 200ms | 60x |
| Storage size | 6 TB | ~19 GB | 315x smaller |
| Monthly cost | $4,000 (RDS compute + storage + snapshots) | $1,800 ($1,500 ClickHouse Cloud + $300 remaining SQL Server for OLTP) | $2,200/month savings |
Query performance numbers are from production. The most common query pattern—sampling time-series data for a device or device group over a date range—returns in milliseconds, not seconds. Bulk exports returning hundreds of megabytes complete in under 500ms, where network transfer is the bottleneck, not ClickHouse.
The Real Win: Cost Trajectory
The $2,200/month savings tells only part of the story. The bigger win is what happens as data grows.
The migration reduced the analytical footprint and monthly bill. Those are measured outcomes for this workload, not a guarantee that cost stays flat as any dataset grows.
ClickHouse writes sorted parts and merges them in the background. Compression, insert shape, query concurrency and compute sizing all affect its cost trajectory.
Synthetic Daily Aggregation Example
A daily summary groups events by entity and date, then computes aggregates over a numeric value. These records are invented solely to show the output shape:
| entity_id | date | average_value | readings |
|---|---|---|---|
| 1 | 2024-01-01 | 12.5 | 4 |
| 2 | 2024-01-01 | 18.0 | 6 |
The identifiers, dates, values and counts above are synthetic. They do not describe the migration or its performance.
Query Concurrency
Concurrency testing was part of the migration. Test representative dashboard reads alongside ingestion rather than treating a fast isolated query as proof of capacity.
ClickHouse Gotchas to Watch For
ClickHouse is powerful, but it has quirks that can trip you up. Here's what to watch for:
ReplacingMergeTree Quirks
Data isn't deduplicated until background merges run. If you insert a duplicate row and immediately query, you might see both. For "latest value" queries, you need the FINAL keyword or explicit deduplication logic.
For a small latest-state table, FINAL can resolve replacement at read time. On a large history table, measure its cost and consider a bounded aggregation that selects the latest version.
ClickHouse Isn't PostgreSQL
ClickHouse is OLAP, not OLTP. Adjustments we had to make:
- No UPDATE or DELETE in the traditional sense. Use ALTER TABLE ... DELETE (async mutation) or insert new rows with higher version numbers for ReplacingMergeTree.
- NULL handling is explicit. Columns are NOT NULL by default. Use
Nullable(Type)explicitly if you need nulls. - Case-sensitive identifiers.
DeviceIDis different fromdeviceid. Stick to a convention. - DateTime64(3) for millisecond precision, not
TIMESTAMP. We initially usedDateTimeand lost sub-second precision.
If you're coming from PostgreSQL or SQL Server, the ClickHouse learning modules are well worth your time. They cover these differences systematically and saved us from several early mistakes.
Lambda Connection Management
Each Lambda cold start opens a new HTTPS connection. ClickHouse Cloud handles this well, but we saw occasional spikes in connection establishment latency during traffic bursts. Solution: reuse connections in warm containers (global variable in Python) and implement exponential backoff on connection failures.
Materialized View Gotchas
Incremental materialized views process new inserts. Historical rows need an explicit backfill into the target. Validate that backfill independently before relying on the derived table.
Monitor failures explicitly. Source-insert and view-error behavior depends on settings. Inspect execution logs and compare source and target expectations.
Profile the write path. A join inside a materialized view can multiply memory use under concurrent inserts. We later reduced per-insert MV memory by 95% using a dictionary. The memory measurement article explains that technique and the metrics involved.
Dictionaries for Reference Metadata
A dictionary can avoid repeatedly fetching slowly changing reference data from an external service at query time. Choose its layout, refresh policy and failure behavior from the lookup requirements.
Account for stale values during refresh and source failures.
ClickHouse Cloud Pricing
ClickHouse Cloud pricing is compute-based, not storage-based. Long-running analytical queries (full table scans) can spike costs. We addressed this by:
- Set
max_execution_timeto a timeout appropriate to the application. - Monitoring
system.query_logfor expensive queries - Dashboard query optimization: pre-computed MVs instead of on-the-fly joins
Through publication, our ClickHouse Cloud bill held at ~$1,500/month despite growing data volume, thanks to these optimizations.
ASOF JOIN Edge Cases
ASOF JOIN matches on equality keys and an ordered inequality. Confirm the supported algorithm and test boundary cases with your ClickHouse version.
A closest-preceding match can still be stale. Carry enough timestamp information to check freshness against the application’s requirements instead of treating every match as current.
When ClickHouse Is (and Isn't) the Right Choice
ClickHouse transformed our IoT analytics platform. But it's not a universal solution. Here's our decision framework:
ClickHouse is excellent for:
- High-volume time-series data. Large append-only histories fit ClickHouse’s analytical storage model.
- Read-heavy analytical workloads. Dashboards, reports, aggregations—this is ClickHouse's sweet spot.
- Aggregation-heavy queries. GROUP BY device, date, hour—columnar storage shines here.
- Mostly immutable data. Sensor readings don't change after they're recorded.
- Real-time materialized views and ASOF JOINs. These features enable analytics that were impossible in SQL Server.
Consider alternatives if:
- You need ACID transactions across multiple rows. ClickHouse isn't built for transactional workloads. Use PostgreSQL or MySQL.
- Frequent point updates to existing rows. If you're constantly updating individual rows, PostgreSQL is a better fit.
- Complex many-to-many JOINs are your primary pattern. ClickHouse can do JOINs, but it's optimized for denormalized data and columnar scans.
- You need sub-millisecond ingestion latency. ClickHouse batches writes for efficiency. For real-time streaming, consider Kafka + ClickHouse.
The Broader Lesson: Right Tool for the Scale You're At
SQL Server served our client well for the first million rows. When the dataset grew to billions and query patterns shifted toward time-series analytics, ClickHouse was the right evolution.
This isn't about ClickHouse being "better"—it's about matching database architecture to workload characteristics. SQL Server excels at transactional workloads with complex relationships. ClickHouse excels at analytical queries over append-only time-series data. Use both, where appropriate.
The results speak for themselves:
- 1.3 billion rows migrated from SQL Server to ClickHouse Cloud
- Sub-20ms time-series queries, under 500ms bulk exports (network-bound)
- 315x storage reduction: 6 TB SQL Server to approximately 19 GB ClickHouse
- $2,200/month savings at cutover: $4,000 to $1,800 a month, including the SQL Server kept for OLTP (approximately $26K/year)
If your IoT platform or sensor network is outgrowing its relational database, I'm happy to compare notes on whether ClickHouse fits your scale and query patterns.
Resources
- ClickHouse Documentation — Getting started guide and core concepts for ClickHouse.
- ClickHouse Cloud Architecture — Deep dive into SharedMergeTree and the separation of compute and storage.
- ReplacingMergeTree Engine — How deduplication works with version columns and FINAL queries.
- Materialized Views in ClickHouse — Cascading MVs, target tables, and real-time aggregation patterns.
- ASOF JOIN Documentation — Syntax and usage for time-series correlation joins.
- ClickHouse Codecs — Column-level compression options including Delta, ZSTD, and LZ4.
- AWS Lambda Best Practices — Connection pooling, error handling, and performance optimization for Lambda.
- ClickHouse Performance Optimization — Query tuning, indexing strategies, and hardware considerations.