๐Ÿ“ŠData Engineering

Apache Druid

Apache Druid

A real-time analytics database. Sub-second query responses.

Detailed Explanation

Apache Druid is a high-performance analytics database designed to process real-time OLAP (Online Analytical Processing) queries on large-scale datasets with sub-second response times. Developed at Metamarkets and released as open source in 2012, it is used by companies that handle large volumes of traffic, such as Netflix, Airbnb, and eBay.

Druid's core architecture combines columnar storage, inverted indexes, and bitmap indexes to enable fast filtering and aggregation. Data is partitioned into time-based segments and stored in a distributed manner, which enables efficient queries on time-series data.

It supports both real-time data ingestion and batch ingestion. It can ingest data in real time from streaming sources such as Kafka and Kinesis while also loading batch data from HDFS and S3. Ingested data is automatically converted into optimized segments and stored in deep storage.

It supports Druid SQL, so data can be analyzed with standard SQL queries, and Native JSON queries are also provided. It integrates with major BI tools such as Superset, Tableau, and Looker and is used to build dashboards and reports.

Code Example

SQL Click to copy
-- Apache Druid OLAP ์ฟผ๋ฆฌ ์˜ˆ์ œ

-- ==========================================
-- 1. ๊ธฐ๋ณธ ์ง‘๊ณ„ ์ฟผ๋ฆฌ (์‹œ๊ฐ„ ๊ธฐ๋ฐ˜)
-- ==========================================

-- ์ผ๋ณ„ ๋งค์ถœ ์ง‘๊ณ„
SELECT
  TIME_FLOOR(__time, 'P1D') AS day,
  COUNT(*) AS transaction_count,
  SUM(amount) AS total_revenue,
  COUNT(DISTINCT user_id) AS unique_users,
  AVG(amount) AS avg_transaction
FROM sales_events
WHERE __time >= TIMESTAMP '2024-01-01'
  AND __time < TIMESTAMP '2024-02-01'
GROUP BY TIME_FLOOR(__time, 'P1D')
ORDER BY day;

-- ==========================================
-- 2. ๋‹ค์ฐจ์› ๋ถ„์„ (GROUPING SETS)
-- ==========================================

-- ์นดํ…Œ๊ณ ๋ฆฌ, ์ง€์—ญ๋ณ„ ๋ณตํ•ฉ ์ง‘๊ณ„
SELECT
  COALESCE(category, 'ALL') AS category,
  COALESCE(region, 'ALL') AS region,
  COUNT(*) AS events,
  SUM(revenue) AS total_revenue
FROM page_views
WHERE __time >= CURRENT_TIMESTAMP - INTERVAL '7' DAY
GROUP BY GROUPING SETS (
  (category, region),
  (category),
  (region),
  ()
)
ORDER BY category, region;

-- ==========================================
-- 3. ํผ๋„ ๋ถ„์„ ์ฟผ๋ฆฌ
-- ==========================================

-- ์‚ฌ์šฉ์ž ์ „ํ™˜ ํผ๋„
SELECT
  step,
  COUNT(DISTINCT user_id) AS users,
  COUNT(DISTINCT user_id) * 100.0 /
    FIRST_VALUE(COUNT(DISTINCT user_id)) OVER (ORDER BY step) AS conversion_rate
FROM (
  SELECT
    user_id,
    MIN(CASE WHEN event_type = 'page_view' THEN 1 END) AS step1,
    MIN(CASE WHEN event_type = 'add_to_cart' THEN 2 END) AS step2,
    MIN(CASE WHEN event_type = 'checkout' THEN 3 END) AS step3,
    MIN(CASE WHEN event_type = 'purchase' THEN 4 END) AS step4
  FROM user_events
  WHERE __time >= CURRENT_TIMESTAMP - INTERVAL '30' DAY
  GROUP BY user_id
)
UNPIVOT (step FOR step_name IN (step1, step2, step3, step4))
WHERE step IS NOT NULL
GROUP BY step;

-- ==========================================
-- 4. ์‹ค์‹œ๊ฐ„ ๋Œ€์‹œ๋ณด๋“œ ์ฟผ๋ฆฌ
-- ==========================================

-- ์ตœ๊ทผ 5๋ถ„ ์‹ค์‹œ๊ฐ„ ๋ฉ”ํŠธ๋ฆญ
SELECT
  TIME_FLOOR(__time, 'PT1M') AS minute,
  datasource,
  COUNT(*) AS requests_per_min,
  APPROX_QUANTILE_DS(response_time, 0.95) AS p95_latency,
  APPROX_QUANTILE_DS(response_time, 0.99) AS p99_latency
FROM request_logs
WHERE __time >= CURRENT_TIMESTAMP - INTERVAL '5' MINUTE
GROUP BY 1, 2
ORDER BY 1 DESC;

-- ==========================================
-- 5. ๋ฐ์ดํ„ฐ ์ˆ˜์ง‘ ์ŠคํŽ™ (Kafka Ingestion)
-- ==========================================

-- JSON ํ˜•์‹์˜ Kafka Ingestion Spec
/*
{
  "type": "kafka",
  "spec": {
    "dataSchema": {
      "dataSource": "sales_events",
      "timestampSpec": {
        "column": "event_time",
        "format": "iso"
      },
      "dimensionsSpec": {
        "dimensions": [
          "user_id",
          "product_id",
          "category",
          {"name": "price", "type": "double"},
          "region"
        ]
      },
      "metricsSpec": [
        {"type": "count", "name": "count"},
        {"type": "longSum", "name": "quantity", "fieldName": "quantity"},
        {"type": "doubleSum", "name": "revenue", "fieldName": "revenue"},
        {"type": "HLLSketchBuild", "name": "unique_users", "fieldName": "user_id"}
      ],
      "granularitySpec": {
        "type": "uniform",
        "segmentGranularity": "HOUR",
        "queryGranularity": "MINUTE",
        "rollup": true
      }
    },
    "ioConfig": {
      "topic": "sales-events",
      "consumerProperties": {
        "bootstrap.servers": "kafka:9092"
      },
      "taskCount": 3,
      "replicas": 2
    },
    "tuningConfig": {
      "type": "kafka",
      "maxRowsInMemory": 100000,
      "maxRowsPerSegment": 5000000
    }
  }
}
*/

How It's Used in Practice

PM: "The real-time dashboard is too slow. Users are waiting more than 10 seconds."

Data Engineer: "We're currently aggregating with Elasticsearch, but the data volume has grown too large. If we migrate to Druid, sub-second responses are possible."

Tech Lead: "Can we ingest in real time directly from Kafka? What kind of latency should we expect?"

Data Engineer: "Yes, ingestion latency is usually under 1 minute. If you pre-aggregate with rollup, queries get even faster."

Interviewer: "Please explain the differences between Druid and ClickHouse."

Candidate: "Both are columnar databases for OLAP, but Druid is more optimized for time-series data and real-time ingestion, while ClickHouse is stronger at more general-purpose analytical queries. Druid does pre-aggregation through rollup by default, while ClickHouse retains more raw data."

Interviewer: "How do you manage data retention policies in Druid?"

Candidate: "You set retention rules in the Coordinator. You can define rules so that recent data stays on Historical nodes, while older data goes to a cold tier or is deleted."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Reviewer: "This query uses COUNT(DISTINCT user_id), which can be slow on large datasets."

Developer: "I did it that way because I need an exact count, but is there an alternative?"

Reviewer: "If slightly lower accuracy is acceptable, use APPROX_COUNT_DISTINCT or HyperLogLog sketches. If you precompute them at ingestion time with HLLSketchBuild, queries become much faster."

Cautions

Related Terms

Learn More