Database, warehouse, lake, middle platform, lakehouse: one e-commerce order chain explains all five and why lakehouse isn't 'lake plus warehouse'
Stop memorizing concepts: the middle platform isn't a big data warehouse, and lakehouse isn't 'lake + warehouse' — explain database, data warehouse, data lake, middle platform, and lakehouse in one go through an e-commerce order placement chain
Author: Rain的Java大神之路 Tags: Backend, Big Data, Database
"The company already has MySQL, Hive and a data lake — why do we still need lakehouse? Is the data middle platform just a bigger data warehouse?"
This question appears frequently in interviews for big data development, Java backend and architecture roles at large companies, and it tends to confuse people in real work too. Today we don't pile up jargon; instead, we start from the e-commerce order placement chain and explain the boundaries of the five concepts, architecture evolution, Iceberg/Hudi/Paimon selection, and engineering pitfalls like small files, CDC, and schema evolution thoroughly. It's suitable for interview prep and for friends doing data platform selection.
1. Use an e-commerce scenario to string together the five concepts
Assume a user has just placed an order in an e-commerce app:
- The order is written to MySQL, and inventory is deducted at the same time. No overselling, no duplicate deduction — this is a database.
- MySQL's Binlog goes through Flink CDC into Kafka or a real-time computation chain. Order logs, user behavior tracking, and image metadata are stored in object storage — this is a data lake.
- Spark and Flink clean and model the raw data, forming order details, user summaries and business metrics for BI queries — this is a data warehouse.
- The same order data is no longer copied separately to lake and warehouse; instead it's written as Iceberg, Hudi or Paimon tables, supporting Upsert, snapshots and stream-batch reads — this is lakehouse.
- "GMV", "active users" and "risk customers" are turned into unified metrics, labels and APIs. Marketing, recommendation and risk control all call the same service — this is the data middle platform.
So these are not about one replacing another; they solve different problems:
| Concept | Plain analogy | Core responsibility | One-sentence memory |
|---|---|---|---|
| Database | Cash register, cash ledger | Carry online transactions | Manages the "present", needs accuracy and speed |
| Data warehouse | Accounting office, financial statements | Unify historical analysis conventions | Manages the "past", needs to calculate clearly |
| Data lake | Raw material warehouse | Low-cost storage of all raw data | Store it first, mine later |
| Data middle platform | Central kitchen | Data asset reuse, governance and service-ification | Don't let ten departments each do it once |
| Lakehouse | Smart warehouse with a management system | Provide warehouse capabilities on lake storage | One copy of data, usable for both real-time and offline |
The most important boundary: lakehouse solves the contradiction between "can store it" and "manage it well"; the data middle platform solves the contradiction between "duplicate construction" and "conflicting metrics". The two can cooperate hierarchically, but they cannot replace each other.
2. Where do the five actually differ? One table makes it clear
| Dimension | Database OLTP | Data warehouse OLAP | Data lake | Data middle platform | Lakehouse |
|---|---|---|---|---|---|
| Core positioning | Online business transactions | Analysis and business decisions | Centralized raw data storage | Reusable data capability | Unified base for lake and warehouse |
| Data form | Structured, current state | Structured, historical and subject-oriented | Structured, semi-structured, unstructured | Metrics, labels, APIs, asset catalog | All data types and structured tables |
| Typical storage | Row store, high-performance disk | Column store, MPP or distributed storage | HDFS, S3, OSS | Depends on underlying lakehouse or service layer | Object storage/HDFS + open table formats |
| Schema | Strong constraint on write | Schema-on-Write | Schema-on-Read | Driven by metadata and metric definitions | Balance between write-time constraints and flexible evolution |
| Write method | High-frequency small transactions, row-level insert/update/delete | Batch ETL, overwrite or append | Append-write dominant | Service-ified output | Stream-batch writes, Upsert, ACID |
| Query method | Index point lookup, millisecond response | Large-range scan and aggregation | Exploratory read, on-demand processing | Unified API or metric query | Interactive analysis, stream read, batch read, incremental read |
| Freshness | Millisecond | Second to T+1 | Depends on processing chain | Depends on service and underlying SLA | Second, minute to hour |
| Cost | Relatively high | Medium high | Low | High construction and organizational cost | Low storage cost + elastic compute |
| Typical tech | MySQL, Oracle, PostgreSQL, OceanBase | Hive, ClickHouse, Doris, StarRocks, MaxCompute | HDFS, S3, OSS, Parquet, ORC | OneData, OneID, OneService, Dataphin | Iceberg, Hudi, Paimon, Delta Lake |
| Biggest risk | Dragged down by analytical queries | Lack of flexibility, long chains | Becomes a "data swamp" | Built for the sake of building, no one reuses | Small files, metadata bloat, concurrency conflicts |
A more technical summary:
The database guarantees transaction correctness, the data warehouse guarantees analytical conventions, the data lake guarantees raw completeness, the middle platform guarantees asset reuse, and lakehouse guarantees that one copy of data has both low-cost storage and data warehouse management capabilities.
3. Why did these layers grow out one by one?
Data architecture isn't upgraded to "look advanced"; every time it's forced by real problems.
Early common Lambda architectures maintain both a batch chain and a stream chain:
- Offline side: Hive/Spark runs T+1;
- Real-time side: Kafka/Flink calculates minute-level or second-level metrics;
- The same GMV requires two sets of code and two copies of storage;
- Backfilling requires separate real-time and offline backfills, then reconciliation again.
Public practices from Taotian, vivo and others have mentioned similar problems: real-time and offline storage isn't unified, the common DWS layer is hard to reuse, chains are computed repeatedly, and after backfill inconsistency easily reappears.
The goal of lakehouse isn't to stitch two architecture diagrams into one, but to achieve:
- One copy of data, no repeated migration between lake and warehouse;
- Native support for mainstream open table formats;
- Stream writes, batch compute and interactive queries share data;
- Unified governance of metadata, permissions, lineage and lifecycle.
Note that lakehouse unifies the storage and table format base, but it doesn't mean all queries must be executed by the same engine. ClickHouse and Doris can still serve as acceleration layers for high-SLA reports.
4. Database and data warehouse: one manages transactions, the other manages analysis
4.1 Why can't analytical queries hit the business database directly?
Databases typically use row storage, B+ tree indexes, MVCC and locking for high-concurrency small transactions. They care about "was this order written correctly", not "what was the profit margin of each category over the past three years".
The following monthly report SQL, if run directly against the transaction primary database, can slow down live business through full table scans, long transactions and IO contention:
-- Bad example: running a large-range statistical analysis directly on the business primary database
SELECT DATE_FORMAT(created_at, '%Y-%m') AS month,
COUNT(*) AS order_cnt
FROM orders
WHERE created_at > '2023-01-01'
GROUP BY DATE_FORMAT(created_at, '%Y-%m');
Transaction queries should use appropriate composite indexes:
ALTER TABLE orders
ADD INDEX idx_uid_status_ctime (user_id, status, created_at);
EXPLAIN
SELECT id, order_no, amount
FROM orders
WHERE user_id = 1001
AND status = 1
ORDER BY created_at DESC
LIMIT 20;
Index design highlight:
user_idandstatusare equality conditions, put them first;created_atis for sorting, put it last. This narrows the scan range and can also use index orderliness to reduce filesort. Whether it's a covering index still depends on actual SELECT fields andEXPLAIN.
Analytical traffic should go through read-only replicas, CDC into warehouse or lake. Don't tie the boss's dashboard to users' payment requests on the same primary database.
Also, database interviews often follow up on MVCC:
-- Snapshot read: read a consistent view via MVCC
SELECT * FROM `order` WHERE id = 1;
-- Current read: read latest data with locks
SELECT * FROM `order` WHERE id = 1 FOR UPDATE;
Under MySQL InnoDB's Repeatable Read isolation level, a normal snapshot read and a locking current read are not the same thing. Preventing phantom reads on current reads involves Next-Key Lock, not just a simple "RR never has phantom reads".
4.2 Data warehouse layering isn't just about creating more tables
The core of a data warehouse is to process data from multiple systems into a set of metrics everyone agrees on. Common layering is as follows:
| Layer | Main responsibility |
|---|---|
| ODS | Keep raw data structure from source systems for traceability |
| DWD | Clean, deduplicate, standardize, preserve the finest business facts |
| DWS | Light aggregation by subject and common grain |
| ADS | Serve specific scenarios like reports, risk control, marketing |
In modeling methods, Inmon leans toward top-down enterprise-level normalization, while Kimball leans toward dimensional modeling and star schemas. Domestic internet projects commonly use Kimball + layered modeling.
A DWD order detail table can be designed like this:
CREATE TABLE dwd_order_detail (
order_id BIGINT COMMENT 'Order ID',
user_id BIGINT COMMENT 'User ID',
sku_id BIGINT COMMENT 'Product SKU ID',
order_amount DECIMAL(16,2) COMMENT 'Actual payment amount',
create_time TIMESTAMP COMMENT 'Order placement time',
dt DATE COMMENT 'Partition date'
) ENGINE=OLAP
DUPLICATE KEY(order_id)
COMMENT 'E-commerce order detail fact table'
PARTITION BY RANGE(dt) ()
DISTRIBUTED BY HASH(order_id) BUCKETS 10
PROPERTIES (
"replication_num" = "3",
"compression" = "ZSTD"
);
The key in the ODS-to-ADS process isn't just running SQL through, but placing deduplication and metric conventions in the right place:
-- DWD: keep the latest row per order based on update_time
INSERT OVERWRITE TABLE dwd_order_di PARTITION (dt = '${bizdate}')
SELECT
order_id,
user_id,
sku_id,
CAST(amount AS DECIMAL(18,2)) AS amount,
pay_time,
update_time
FROM (
SELECT
order_id,
user_id,
sku_id,
amount,
pay_time,
update_time,
ROW_NUMBER() OVER (
PARTITION BY order_id
ORDER BY update_time DESC
) AS rn
FROM ods_order_inc
WHERE dt = '${bizdate}'
) t
WHERE rn = 1;
-- DWS: common grain aggregation, reused across application scenarios
INSERT OVERWRITE TABLE dws_trade_user_1d PARTITION (dt = '${bizdate}')
SELECT
user_id,
COUNT(DISTINCT order_id) AS order_cnt,
SUM(amount) AS gmv,
MAX(pay_time) AS last_pay_time
FROM dwd_order_di
WHERE dt = '${bizdate}'
AND pay_time IS NOT NULL
GROUP BY user_id;
-- ADS: serve applications, don't redefine GMV in reports
SELECT user_id, order_cnt, gmv
FROM dws_trade_user_1d
WHERE dt = '${bizdate}'
AND gmv > 0;
For Hive/ORC scenarios, summary tables can also be stored with date partitions:
CREATE TABLE dws_trade_user_1d (
user_id BIGINT COMMENT 'User ID',
order_cnt BIGINT COMMENT 'Order count for the day',
pay_amt DECIMAL(18,2) COMMENT 'Payment amount for the day'
)
PARTITIONED BY (dt STRING)
STORED AS ORC;
The most valuable sentence about data warehouses: metric conventions should be settled in DWS and the metric layer, not scattered across twenty report SQLs. Layering decouples ingestion, common processing and scenario applications so the same common logic is computed only once.
Historical dimensions also need designs like zipper tables and slowly changing dimensions, otherwise today's user level overwrites yesterday's data and historical order analysis "travels through time".
5. Data lake and data middle platform: one isn't a landfill, the other isn't a big data warehouse
5.1 Data lake lowers the storage threshold, not the governance threshold
A data lake typically consists of HDFS/S3/OSS and formats like Parquet, ORC, JSON. It suits data like logs, IoT, audio/video, model samples — "you can't say yet how it'll be used later".
But if you only have bare files without metadata catalogs, permissions, quality, lineage and lifecycle management, the data lake quickly becomes a data swamp:
- Several PB stored, no one knows what tables exist;
- Found the table, don't know what the fields mean;
- Want to delete, but fear some model still uses it;
- Upstream errors can't locate which reports are affected.
So entering the lake should at least complete Catalog registration, Owner assignment, quality rules and lineage collection. Tools like Apache Atlas and DataHub can handle part of it, but tools can't replace governance responsibility.
5.2 The heart of a data middle platform is OneData, OneID, OneService
The data middle platform isn't a specific database, nor is it "build another super data warehouse". It's more like an asset-ification and reuse mechanism:
- OneData: unify models, metrics and statistical conventions;
- OneID: unify entity identifiers like users, customers, merchants;
- OneService: unify data delivery through APIs, metric services, and label services.
Supporting capabilities include master data management (MDM), metadata catalogs, lineage, quality, permissions, audit and data asset lifecycle.
Many middle platform projects fail not because of weak tech, but because no one is willing to pay for reuse: business side complains about slow onboarding, the middle platform team is far from business, and eventually it becomes a centralized data extraction department.
A safer path: first pick a metric or label that's genuinely reused by multiple business lines as a pilot, give assets an Owner, SLA and reuse-rate metrics, then gradually platformize. Don't build a "company-level big middle platform" first and then hunt across the company for needs.
6. The core of lakehouse isn't object storage, it's the table format
Parquet files on object storage don't automatically gain transaction capabilities. What actually gives the "lake" warehouse capabilities is a table format like Iceberg, Hudi, Paimon, or Delta Lake.
Through metadata, transaction logs, snapshots, manifest files or LSM structures, they provide on top of files:
- ACID or table-level transaction commits;
- Row-level update, delete and Upsert;
- Schema evolution;
- Snapshot isolation and time travel;
- Incremental reads;
- Multi-engine sharing;
- File statistics and data skipping.
6.1 How to choose among the four major table formats?
| Dimension | Iceberg | Hudi | Paimon | Delta Lake |
|---|---|---|---|---|
| Design DNA | Open table format, consistent multi-engine access | Incremental processing and Upsert | Flink-native real-time lakehouse | Spark/Databricks ecosystem |
| Metadata/Structure | metadata.json → manifest list → manifest → data file |
.hoodie/ Timeline |
LSM-Tree + Snapshot | _delta_log/ |
| Write characteristics | Snapshot commit, optimistic concurrency | CoW/MoR, strong row-level updates | LSM append-write + background compaction | Smooth Spark ecosystem writes |
| Schema evolution | Strong, based on field IDs | Supported | Supported | Supported |
| Incremental read | Snapshot diff | Native Incremental Query | Changelog incremental consumption | Change Data Feed etc. |
| Highlight capabilities | Hidden partitioning, partition evolution, multi-engine | CoW/MoR, indexing, CDC | Primary key tables, Partial Update, stream-batch unity | Deletion Vectors, Liquid Clustering |
| More suitable for | Spark/Flink/Trino/StarRocks coexistence, large table analysis | High-frequency CDC, Upsert, Hive migration | Flink real-time chains, second-level freshness | Databricks tech stack |
In some project benchmarks, Paimon achieves roughly 1-3 seconds end-to-end latency at ten-thousand-level TPS, Iceberg high-frequency stream writes are typically several seconds to ten-plus seconds, Hudi MoR writes fast but reads have log merge costs. These numbers are heavily affected by version, Checkpoint, file size, storage medium and query method; don't treat them as general benchmarks.
For real selection, just remember three questions: write-heavy or read-heavy? How high is the real-time requirement? Is the main compute stack Flink or Spark?
| Scenario | Preferred choice |
|---|---|
| Multi-engine sharing, PB-level analysis, strong schema evolution | Iceberg |
| Spark-dominant, high-frequency Upsert/CDC | Hudi |
| Flink-dominant, real-time primary key tables and Changelog | Paimon |
| Databricks/Spark integrated system | Delta Lake |
6.2 Iceberg: snapshots, hidden partitioning and time travel
An Iceberg Append commit isn't just "write another Parquet file"; it generates a new snapshot through atomic metadata switch:
Table table = catalog.loadTable(TableIdentifier.of("db", "orders"));
AppendFiles append = table.newAppend();
append.appendFile(
DataFiles.builder(table.spec())
.withPath("/warehouse/orders/data/00000-0-abc.parquet")
.withFileSizeInBytes(1024 * 1024)
.build()
);
// Atomic commit: readers see either the old snapshot or the new one
append.commit();
Snapshot current = table.currentSnapshot();
long snapshotId = current.snapshotId();
Old snapshots are retained for a while, so you can read historical versions by snapshot or time, and roll back erroneous batches.
Spark integration and CDC merge can be written like:
SparkSession spark = SparkSession.builder()
.appName("LakehouseDemo")
.config(
"spark.sql.extensions",
"org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions"
)
.config(
"spark.sql.catalog.my_catalog",
"org.apache.iceberg.spark.SparkCatalog"
)
.config("spark.sql.catalog.my_catalog.type", "hive")
.getOrCreate();
spark.sql(
"CREATE TABLE IF NOT EXISTS my_catalog.db.order_dwd (" +
"order_id STRING, user_id STRING, amount DECIMAL(10,2), ts TIMESTAMP" +
") USING iceberg PARTITIONED BY (days(ts))"
);
spark.sql(
"MERGE INTO my_catalog.db.order_dwd t " +
"USING cdc_source_view s " +
"ON t.order_id = s.order_id " +
"WHEN MATCHED THEN UPDATE SET * " +
"WHEN NOT MATCHED THEN INSERT *"
);
Dataset<Row> oldData = spark.read()
.format("iceberg")
.option("snapshot-id", 3821550127949089987L)
.load("my_catalog.db.order_dwd");
For a user behavior table, you can also configure hidden partitioning, target file size and Merge-on-Read:
CREATE TABLE lake.db.user_behavior (
user_id BIGINT,
behavior STRING COMMENT 'click/view/buy',
ts TIMESTAMP,
product_id BIGINT
)
USING iceberg
PARTITIONED BY (days(ts), bucket(16, user_id))
TBLPROPERTIES (
'format-version' = '3',
'write.target-file-size-bytes' = '268435456',
'write.merge.mode' = 'merge-on-read'
);
-- Read historical versions by time or snapshot
SELECT *
FROM lake.db.user_behavior
TIMESTAMP AS OF '2026-10-01 00:00:00';
SELECT *
FROM lake.db.user_behavior
VERSION AS OF 1234567890;
-- CDC row-level updates and deletes
MERGE INTO lake.db.user_behavior AS t
USING ods.user_behavior_cdc AS s
ON t.user_id = s.user_id AND t.ts = s.ts
WHEN MATCHED AND s.op = 'D' THEN DELETE
WHEN MATCHED THEN UPDATE SET *
WHEN NOT MATCHED THEN INSERT *;
Why is hidden partitioning fast?
days(ts)partition info is written into metadata. When queries filter byts, the engine first prunes manifest list and manifests, then uses column statistics min/max to skip files. Many data files never even need to be opened.
Time travel isn't just for querying; it can also recover from mistakes:
CALL system.rollback_to_snapshot('ods_order', 123456789);
Spark DataFrame writes and snapshot rollback can be combined, but note: the rollback statement in the example shouldn't unconditionally follow every normal write; it should be triggered by exception handling or an operations workflow.
public void appendOrders(
SparkSession spark,
Dataset<Row> orderDF) {
orderDF.writeTo("iceberg_ods.dwd_order_iceberg")
.option("write-format", "parquet")
.option("merge-schema", "true")
.append();
}
public void rollback(SparkSession spark, long snapshotId) {
spark.sql(
"CALL iceberg_ods.system.rollback_to_snapshot(" +
"'iceberg_ods.dwd_order_iceberg', " + snapshotId + ")"
);
}
Iceberg's schema evolution is based on field IDs rather than simply column position. Adding columns, renaming, etc., can modify only metadata without rewriting historical Parquet files.
table.updateSchema()
.addColumn("channel", Types.StringType.get(), "traffic channel")
.commit();
But compatible changes and breaking changes must be handled separately. Adding a nullable field is relatively safe; operations like int → string or changing business meaning are better done with a new column, dual write for gray release, and necessary data backfill. Don't expect the table format to solve semantic problems for you.
6.3 Flink CDC + Iceberg: the backbone real-time ingestion chain
The following Flink SQL shows the complete chain from MySQL Binlog to Iceberg:
CREATE TABLE user_source (
database_name STRING METADATA FROM 'source.database' VIRTUAL,
table_name STRING METADATA FROM 'source.table' VIRTUAL,
id DECIMAL(20, 0) NOT NULL,
name STRING,
phone_number STRING,
PRIMARY KEY (id) NOT ENFORCED
) WITH (
'connector' = 'mysql-cdc',
'hostname' = 'mysql-host',
'database-name' = 'inventory',
'table-name' = 'users',
'username' = 'flinkuser',
'password' = '***',
'scan.incremental.snapshot.enabled' = 'true'
);
CREATE TABLE all_users_sink (
database_name STRING,
table_name STRING,
id DECIMAL(20, 0) NOT NULL,
name STRING,
PRIMARY KEY (database_name, table_name, id) NOT ENFORCED
) WITH (
'connector' = 'iceberg',
'catalog-name' = 'iceberg_catalog',
'catalog-type' = 'hive',
'warehouse' = 's3://lakehouse/warehouse',
'format-version' = '2'
);
INSERT INTO all_users_sink
SELECT * FROM user_source;
Two details are practical:
scan.incremental.snapshot.enabled=truefor incremental snapshot reads, reducing lock pressure during the full phase;- The composite primary key
(database_name, table_name, id)avoids primary key ID conflicts after sharding.
The Java DataStream approach is similar:
StreamExecutionEnvironment env =
StreamExecutionEnvironment.getExecutionEnvironment();
env.enableCheckpointing(60000);
MySqlSource<String> source = MySqlSource.<String>builder()
.hostname("mysql-host")
.port(3306)
.databaseList("order_db")
.tableList("order_db.t_order")
.username("flinkuser")
.password("***")
.deserializer(new JsonDebeziumDeserializationSchema())
.build();
DataStream<String> stream = env.fromSource(
source,
WatermarkStrategy.noWatermarks(),
"MySQL CDC"
);
stream.sinkTo(
IcebergSink.forRowData()
.tableLoader(tableLoader)
.build()
);
End-to-end Exactly-Once isn't achieved by just enabling one Checkpoint. It requires cooperation among the CDC Source, Flink Checkpoint, Sink two-phase commit or idempotent writes. Failure recovery, timeout commits and external system semantics all need to be verified.
For incremental consumption, you can use a snapshot ID as the processing boundary; when joining dimensions, guard against "old orders joining new dimensions":
SET snapshot_id = (
SELECT snapshot_id
FROM iceberg_catalog.ods.order_ods.snapshots
ORDER BY committed_at DESC
LIMIT 1
);
INSERT INTO dwd.order_detail_wide
SELECT
o.order_id,
u.user_name,
p.product_name,
o.amount,
o.event_time
FROM (
SELECT *
FROM iceberg_catalog.ods.order_ods
/*+ OPTIONS('snapshot-id' = ${snapshot_id}) */
) o
LEFT JOIN iceberg_catalog.dim.user_dim
FOR SYSTEM_TIME AS OF o.event_time
ON o.user_id = u.user_id
LEFT JOIN iceberg_catalog.dim.product_dim p
ON o.product_id = p.product_id
WHERE o.event_time >
CURRENT_TIMESTAMP - INTERVAL '10' MINUTE;
Here FOR SYSTEM_TIME AS OF embodies the business time semantics: an order placed yesterday should join the user dimension valid yesterday, not the profile changed today.
6.4 Paimon: real-time primary key tables and Partial Update
Paimon's strength is Flink real-time chains. Primary key tables support Upsert on an LSM structure, and can continue stream consumption downstream through Changelog:
CREATE CATALOG paimon_catalog WITH (
'type' = 'paimon',
'warehouse' = 'hdfs:///paimon/warehouse'
);
CREATE TABLE paimon_catalog.dwd.order_detail (
order_id BIGINT,
user_id BIGINT,
amount DECIMAL(18,2),
update_time TIMESTAMP(3),
PRIMARY KEY (order_id) NOT ENFORCED
) WITH (
'bucket' = '4',
'changelog-producer' = 'input'
);
INSERT INTO paimon_catalog.dwd.order_detail
SELECT order_id, user_id, amount, update_time
FROM ods_order_cdc;
You can also declare a deduplication merge strategy so the same primary key keeps the latest record:
CREATE TABLE paimon_order (
order_id BIGINT,
user_id BIGINT,
pay_amt DECIMAL(18,2),
update_time TIMESTAMP(3),
PRIMARY KEY (order_id) NOT ENFORCED
) WITH (
'connector' = 'paimon',
'merge-engine' = 'deduplicate',
'changelog-producer' = 'input'
);
Common changelog-producer configurations include input, lookup, etc. Different modes differ in extra overhead and Changelog completeness; don't just copy parameters without looking at downstream semantics.
Another very useful Paimon feature is Partial Update: the order stream and risk control stream update different fields of the same user-wide table.
CREATE TABLE paimon.dw.dwd_order (
order_id BIGINT,
user_id BIGINT,
amount DECIMAL(18,2),
status STRING,
update_time TIMESTAMP(3),
dt STRING,
PRIMARY KEY (order_id) NOT ENFORCED
)
PARTITIONED BY (dt)
WITH (
'bucket' = '4',
'changelog-producer' = 'lookup',
'snapshot.time-retained' = '7 d'
);
CREATE TABLE paimon.dw.dws_user_wide (
user_id BIGINT,
order_cnt BIGINT,
last_pay_ts TIMESTAMP(3),
risk_score INT,
PRIMARY KEY (user_id) NOT ENFORCED
) WITH (
'merge-engine' = 'partial-update',
'fields.order_cnt.aggregate-function' = 'sum'
);
-- Order stream only updates order fields
INSERT INTO paimon.dw.dws_user_wide
SELECT user_id, order_cnt, last_pay_ts, CAST(NULL AS INT)
FROM order_stream;
-- Risk stream only updates risk fields
INSERT INTO paimon.dw.dws_user_wide
SELECT user_id,
CAST(NULL AS BIGINT),
CAST(NULL AS TIMESTAMP(3)),
risk_score
FROM risk_stream;
Design highlight: traditional Flink Join to build wide tables requires storing lots of state. Partial Update pushes "merge fields by primary key" down to the storage layer, significantly reducing Join state pressure. However, how aggregate fields merge, whether nulls overwrite, and how out-of-order data is handled still need business-defined validation.
Paimon also supports time-based scans and tag management:
SELECT *
FROM paimon_order
/*+ OPTIONS('scan.timestamp-millis'='1730000000000') */;
CALL sys.create_tag('paimon_order', 'before_big_promotion');
6.5 Hudi: CoW/MoR and native incremental query
Hudi's two table types often confuse people:
| Type | Write | Read | Suitable for |
|---|---|---|---|
| CoW, Copy on Write | Rewrites data files on update, higher write amplification | Direct read | Read-heavy, write-light, values read performance |
| MoR, Merge on Read | Changes first written to log, background merge | Read merges Base and Log | Write-heavy, low-latency CDC |
An Upsert write config example:
HoodieWriteConfig cfg = HoodieWriteConfig.newBuilder()
.withPath("hdfs:///hudi/dwd_order")
.forTable("dwd_order")
.withWriteOperationType(WriteOperationType.UPSERT)
.withIndexConfig(
HoodieIndexConfig.newBuilder()
.withIndexType(HoodieIndex.IndexType.BUCKET)
.withBucketIndexEngineType(
BucketIndexEngineType.SIMPLE
)
.withBucketNum(8)
.build()
)
.withStorageConfig(
HoodieStorageConfig.newBuilder()
.parquetMaxFileSize(256L * 1024 * 1024)
.build()
)
.withCompactionConfig(
HoodieCompactionConfig.newBuilder()
.withInlineCompaction(true)
.withMaxNumDeltaCommitsBeforeCompaction(10)
.build()
)
.build();
Three engineering handles here:
- BUCKET index reduces index probe cost under high-concurrency Upsert;
parquetMaxFileSizecontrols file size at the source;- Inline Compaction automatically merges after Delta Commit reaches a threshold.
Hudi's incremental query can read changes after a specific Commit:
Dataset<Row> incremental = spark.read()
.format("hudi")
.option("hoodie.datasource.query.type", "incremental")
.option(
"hoodie.datasource.read.begin.instanttime",
"20260101000000"
)
.load("/warehouse/hudi/orders");
incremental.show();
Metadata like _hoodie_commit_time can serve as the basis for incremental consumption, avoiding downstream rescanning of all historical data. CDC scenarios also commonly configure a precombine field so out-of-order messages retain the correct version according to business time.
7. One copy of data, how to serve BI, real-time compute and AI at the same time?
After unifying the table format, compute engines can be chosen by scenario instead of copying data for every engine switch.
7.1 Federated query: join lake logs with warehouse metrics
SELECT
l.user_id,
o.total_order_cnt,
l.page_view_cnt
FROM iceberg.ods.user_behavior_log l
LEFT JOIN clickhouse.dws.user_order_1d o
ON l.user_id = o.user_id
WHERE l.dt = '2026-10-28'
AND o.dt = '2026-10-28'
LIMIT 1000;
Presto/Trino federated queries suit cross-source analysis, but cross-engine Joins aren't naturally cheap. Large table joins still need to consider broadcast, data skew, network transfer and predicate pushdown.
7.2 External Catalog: StarRocks/Trino query Iceberg directly
CREATE EXTERNAL CATALOG iceberg_lake
PROPERTIES (
'type' = 'iceberg',
'iceberg.catalog.type' = 'hive',
'hive.metastore.uris' = 'thrift://hms:9083'
);
SELECT dt, COUNT(*) AS cnt
FROM iceberg_lake.db.user_behavior
WHERE dt >= '2026-10-01'
GROUP BY dt
ORDER BY dt;
The value of Zero-ETL isn't that "ETL disappears", but that you avoid copying data again just for queries. Cleaning, modeling and quality checks are still needed; data just stops being pointlessly moved.
For high-concurrency, sub-second fixed reports, you can add ClickHouse/Doris/StarRocks, materialized views or caches above the lakehouse. A unified lakehouse base and a high-performance acceleration layer don't conflict.
8. How does the Java side hide multi-engine differences?
If business code is full of "query MySQL here, Hive there, Iceberg next", it quickly becomes a pile of if-else. A strategy router is better.
public interface DataQueryService {
QueryResult query(QueryRequest req);
}
@Service("mysql")
class MySqlQueryService implements DataQueryService {
@Override
public QueryResult query(QueryRequest req) {
return jdbcTemplate.queryForObject(req.getSql(), rowMapper);
}
}
@Service("hive")
class HiveQueryService implements DataQueryService {
@Override
public QueryResult query(QueryRequest req) {
return sparkSql(req.getSql());
}
}
@Service("lakehouse")
class LakehouseQueryService implements DataQueryService {
@Override
public QueryResult query(QueryRequest req) {
return icebergSql(req.getSql(), req.getSnapshotId());
}
}
@Component
@RequiredArgsConstructor
public class DataQueryRouter {
private final Map<String, DataQueryService> serviceMap;
public QueryResult route(QueryRequest req) {
DataQueryService service = serviceMap.get(req.getScene());
if (service == null) {
throw new IllegalArgumentException("Unsupported query scene");
}
return service.query(req);
}
}
Adding a new engine only requires a new implementation and route configuration, not modifying all business callers.
In middle platform scenarios, add metric metadata, permissions, masking, cache and capacity protection before routing:
@Service
public class OneDataServiceGateway {
private final Map<QueryScene, EngineExecutor> router =
new EnumMap<>(QueryScene.class);
private final Cache<String, QueryResult> hotCache =
Caffeine.newBuilder()
.maximumSize(10_000)
.expireAfterWrite(Duration.ofSeconds(30))
.recordStats()
.build();
@PostConstruct
public void init() {
router.put(QueryScene.REALTIME_DASHBOARD, dorisExecutor);
router.put(QueryScene.ADHOC_ANALYSIS, clickHouseExecutor);
router.put(QueryScene.DETAIL_SCAN, paimonExecutor);
}
public QueryResult query(QueryReq req) {
String cacheKey =
req.getMetricCode() + ":" + req.getDimHash();
return hotCache.get(cacheKey, key -> {
// Metrics can only come from the registry; callers can't define their own conventions
MetricDef def =
metricRegistry.get(req.getMetricCode());
accessControl.checkAndMask(def, req);
EngineExecutor executor = router.get(def.getScene());
if (executor == null) {
throw new IllegalStateException("No engine configured");
}
// Query plan includes partition pruning, predicate pushdown optimizations
return executor.execute(def, req);
});
}
}
Expose a unified metric API:
@RestController
@RequestMapping("/api/metric")
public class MetricServiceController {
private final MetricMetadataService metadataService;
private final AccessControl accessControl;
private final QueryPlanBuilder planBuilder;
private final QueryExecutor executor;
@GetMapping("/{metricCode}")
public MetricResult query(
@PathVariable String metricCode,
@RequestParam Map<String, Object> dims) {
MetricMeta meta = metadataService.getByCode(metricCode);
accessControl.checkAndMask(meta, dims);
QueryPlan plan = planBuilder.build(meta, dims);
return executor.execute(plan);
}
}
Production environments also need parameter whitelists, timeouts, rate limiting, circuit breakers, audit and cache consistency. Especially, don't directly concatenate caller-supplied SQL, otherwise a unified gateway becomes a unified "injection entry".
The real value of middle platform code isn't in Spring annotations, but in "metric conventions defined only once, permissions and masking upfront, multi-engine transparent to business".
9. The engineering pitfalls that really set people apart
Knowing concepts is only the entry point; what torments you after going live is usually these details.
| Difficulty | Common root cause or symptom | Solution |
|---|---|---|
| Small file avalanche | High-frequency stream writes, too-short Checkpoint, too many partitions | Batch on write side; target file 256-512MB; Iceberg rewrite_data_files; Hudi Clustering/Compaction; Paimon background Compaction |
| Metadata bloat | Snapshots and Manifests accumulate long-term | expire_snapshots, rewrite_manifests, remove_orphan_files; configure TTL and retention counts |
| Concurrent write conflicts | Multiple jobs modify same table or partition | Optimistic concurrency control with retries; partition/bucket isolation; serialize write entry when necessary |
| CDC loss/duplication/out-of-order | Full+incremental switching, task recovery, message duplication | Flink Checkpoint + two-phase commit; primary key Upsert idempotency; precombine/event time controls versions |
| Stream-batch metric inconsistency | Two sets of code, different time semantics and dedup keys | Define once in DWS; unify primary keys, event time and Watermark; T+1 automatic reconciliation |
| Schema change breaks downstream | Upstream adds/alters columns or business meanings | Field ID evolution; compatible changes gray release; breaking changes use new column, dual write and backfill |
| Slow lake queries | Full table scans, missing statistics and clustering | Partition pruning, predicate pushdown, Z-Order, min/max, Bloom Filter, materialized views and caches |
| Data skew | Hot users, streamers or merchants during promos | Salt spreading, two-stage aggregation, Flink local-global aggregation |
| Write backpressure during promos | Traffic spikes, Checkpoint blocking, concentrate writes in partitions | write.distribution-mode=hash; reasonable scaling; use unaligned Checkpoint when necessary; monitor backpressure and commit time |
| Data swamp | No catalog, Owner, lineage, quality, lifecycle | Register upon ingestion; Atlas/DataHub; build permissions, quality and TTL together |
| Permissions and compliance | Split permissions across engines, sensitive fields like phone numbers exposed | Ranger/Sentry, Catalog unified auth, column-level masking, dynamic masking and audit |
| Cost run-away | Cold data on high-performance media, snapshots retained forever | Hot/cold tiering, object storage infrequent/archive, TTL, elastic compute |
| Middle platform high concurrency | Hot metrics repeatedly hit OLAP during promos | Caffeine/Redis cache, Sentinel rate limiting, read-write separation, circuit breaking and capacity isolation |
| Middle platform built for the sake of building | Assets unused, business onboarding slow | Build by domain, start with strong-demand pilots; measure with reuse rate, onboarding time and SLA |
9.1 Small file governance: "source control + background merging"
Iceberg common operations trio:
CALL lake.system.rewrite_data_files(
table => 'db.user_behavior',
options => map(
'target-file-size-bytes', '268435456',
'min-input-files', '5'
)
);
CALL lake.system.expire_snapshots(
table => 'db.user_behavior',
older_than => TIMESTAMP '2026-10-20 00:00:00',
retain_last => 10
);
CALL lake.system.rewrite_manifests('db.user_behavior');
On the write side, set:
'write.target-file-size-bytes' = '268435456'
Don't blindly shrink Flink Checkpoint to a few seconds for lower latency. High-frequency commits produce many files and snapshots. Vivo's practices even suggest at least 5-minute checkpoint intervals for some scenarios. But this isn't a universal answer: real-time business needs to weigh SLA, recovery time and failure semantics; don't drag end-to-end latency down just to make files look good.
Compaction is commonly triggered every 10-30 minutes, after several Delta Commits, or when file count reaches a threshold. It usually reads old files, writes new files and commits a new snapshot; old snapshots remain readable until commit. What to actually guard against is Compaction competing for CPU and IO with online reads and writes.
9.2 Why do real-time and offline always differ by that 2%?
Common differences hide in three places:
- Different semantics: real-time computes order amount, offline conveniently computes payment amount;
- Different time: one uses event time, the other uses processing time;
- Different dedup: real-time relies on state dedup, offline uses
ROW_NUMBER(), and primary key and out-of-order strategies differ.
Solutions also split into three layers:
- Metric layer: define once in DWS or metric center;
- Technical layer: unify primary keys, idempotent Upsert, event time and Watermark;
- Monitoring layer: T+1 automatic reconciliation; alert and assign Owner when difference rate exceeds threshold.
Lakehouse can reduce duplicate storage and chains, but it won't automatically unify business conventions. Even if you write real-time and offline SQL to the same table, if definitions differ, numbers still won't match.
10. In interviews or technical reviews, how do you give a complete answer?
If you only have 30 seconds, answer like this:
Databases target OLTP, ensuring high concurrency and transaction consistency for online transactions; data warehouses target OLAP, unifying historical analysis conventions through layering and dimensional modeling; data lakes use low-cost storage to keep structured, semi-structured and unstructured raw data; the data middle platform isn't a type of storage but achieves data asset reuse through OneData, OneID and OneService; lakehouse uses open table formats like Iceberg, Hudi and Paimon to provide ACID, Upsert, schema evolution and time travel on lake storage, reducing data copying between lake and warehouse. The five work as layered collaboration, not simple replacement.
If asked further, use this quick reference:
| Follow-up | Answer focus |
|---|---|
| Will the data lake replace the data warehouse? | No. The lake excels at full-volume and flexible storage; the warehouse excels at modeling, conventions and high-performance analysis; lakehouse is a fusion |
| Will lakehouse replace ClickHouse/Doris? | Not necessarily. High-SLA, sub-second core reports may still need dedicated OLAP acceleration layers |
| Is the middle platform a pseudo-concept? | Unified metrics, IDs and services are real needs; the easily dismantled part is an overly centralized organizational form disconnected from business |
| How to choose between Iceberg and Paimon? | Multi-engine and large-table analysis lean Iceberg; Flink real-time primary key tables and Changelog lean Paimon |
| Why not use Lambda anymore? | Two sets of code, conventions and storage costs are too high; lakehouse narrows differences to the compute layer |
| How is time travel implemented? | Immutable data files plus metadata snapshots; reading old versions reads the file set pointed to by the old snapshot |
| How often should small files be merged? | Triggered by file count, commit count, latency and resource levels; there's no universal fixed period |
| What's the relationship between middle platform and data warehouse? | Data warehouse is storage and modeling; middle platform is assets, services and governance; middle platform can sit on top of warehouse or lakehouse |
Finally, don't just say technical terms. Add your project constraints for persuasion: daily data volume, table count, query P99, end-to-end freshness, CDC peak, Compaction cycle, reconciliation difference rate, and why you made this selection.
Closing
This set of concepts can be summed up in one sentence:
The database manages transactions, the data warehouse manages conventions, the data lake manages raw data, the middle platform manages reuse, and lakehouse lets low-cost data also be transactionally and standardly managed.
For implementation, suggest bottom-up: first get the MySQL + CDC + table format basic chain working, then build ODS/DWD/DWS layers and quality systems, and finally settle genuinely reused metrics and labels into middle platform services. Don't chase a "full suite" from the start, or you'll easily spend money building a more complicated reporting platform.
If you're doing lakehouse selection, what currently troubles you most: small files, real-time vs offline mismatch, or not knowing whether to choose Iceberg/Hudi/Paimon? Feel free to comment your data volume and main engine, and we can break it down by specific scenario. If this post is useful, feel free to like, bookmark and save it. Next we'll continue discussing Flink real-time lake ingestion tuning details.
Top 1 of 2 from juejin.cn, machine-translated. The original thread is authoritative.
Like
Go for it