We are designing a Change Data Capture (CDC) bridge that handles:
Ordering: Ensure that changes are processed in the order they occurred in the source.
Schema Evolution: Handle changes to the source schema over time.
Reorg Handling: Handle table reorganization (e.g., in databases that use MVCC, a reorg might change the physical location but log the changes in order).
Replay Safety: The bridge should be safe to use for replaying historical changes without causing duplicate effects or inconsistencies.
Assumptions:
We are building a bridge that reads from a CDC log (like Debezium, or database transaction log) and writes to a target system (like a data warehouse, another database, or a stream).
The source database transaction log provides changes in the order they were committed, and we can rely on that order for changes within a single table/partition. However, note that for distributed systems, we might have to consider ordering across partitions/transactions if the target requires global ordering.
Let's break down each requirement:
Ordering:
We must maintain the order of changes as they appear in the CDC log. This is critical for maintaining data consistency at the target.
However, note that in a distributed system, we might have multiple partitions/tables. We can have two levels of ordering:
a. Global ordering: All changes across the entire database in the order they were committed. This is hard to achieve without a single thread, and even then, if the source is distributed, the log might not have a total order.
b. Per-table/partition ordering: We can guarantee that changes to a single table (or partition) are processed in order. This is more common and often sufficient.
Our bridge should at least maintain per-table/partition ordering. If the target requires global ordering, we might need an additional step to order across tables (which is complex and often not necessary).
Schema Evolution:
As the source schema evolves (e.g., adding a column, changing a data type), the CDC events might have different schemas.
We need to handle these changes gracefully at the target. This might involve:
Mapping the source schema changes to the target schema.
If the target is a schema-on-read system (like many data lakes), we might just store the data as is and let the reader handle it.
If the target is a schema-on-write system (like a relational database), we need to alter the target schema accordingly.
We must be cautious about backward and forward compatibility. For example, if a column is added in the source, we might need to add it in the target. If a column is dropped, we might ignore it in the target.
We might need to maintain a schema registry or use a format that includes schema information (like Avro, Protobuf) to handle evolution.
Reorg Handling:
In some databases (like DB2, Oracle, etc.), a table reorganization might generate a large number of change events that represent the same row but with a new physical location.
These events are typically just updates that set the row to the same values but with a new ID (if there's a row ID) or they might be represented as delete+insert.
We must ensure that these reorg events do not cause unnecessary updates at the target or break ordering.
The key is to recognize that the reorg events are just a special kind of update that does not change the logical row (the primary key and non-key columns remain the same). However, note that sometimes the reorg might change the primary key (if the primary key is a ROWID or similar). In that case, we must update the primary key at the target.
We need to design the bridge to handle such events without causing duplicate rows or inconsistent state.
Replay Safety:
The bridge might be used to replay historical changes (e.g., from a backup of the CDC log). We must ensure that replaying does not cause duplicate changes at the target.
We can achieve this by making the target operations idempotent. For example:
For inserts: if the row already exists, update it? But that might not be the same as the original insert if the row has changed since.
Alternatively, we can use the CDC event's transaction ID and offset (or a combination of source table, primary key, and event time) to deduplicate.
However, note that in a replay, we might be replaying a sequence of events that was already applied. We must have a way to know which events have been applied.
One common approach is to store the last processed offset (or watermark) and only apply events after that. But in a replay, we might want to start from an earlier point.
We can design the bridge to be idempotent by having each event carry a unique identifier (like the log offset) and the target system to record which events have been applied. Then, during replay, we skip already applied events.
Alternatively, if the target is a stream processing system (like Kafka), we can rely on the consumer group offsets. But if we are writing to a database, we need a way to track.
Another idea: use the source's transaction ID and the event's position within the transaction (if available) to deduplicate.
Design Outline:
Let's assume we are building a bridge that reads from a CDC source (like Debezium) and writes to a target database (like PostgreSQL). We'll consider:
The CDC events are in JSON format (or Avro) with a header that includes:
source: table name, database, etc.
op: operation (c=insert, u=update, d=delete, r=read for initial snapshot)
ts_ms: timestamp of the event (or transaction commit time)
offset: a unique identifier for the event in the log (like Kafka offset, or log sequence number)
transaction_id: if available, the transaction ID that the event belongs to.
Steps:
Reading the CDC stream:
We consume the CDC stream in the order provided by the source (per partition). For Kafka, we might have multiple partitions for a table, so we must maintain ordering per partition and then possibly merge for global ordering if required.
We must handle schema evolution: the CDC source might provide a schema for each event (or a schema registry). We can use a library that can handle schema evolution (like Avro) and convert the event to a common format that our bridge understands.
Processing events:
For each event, we extract:
The table name and primary key (if available, the CDC event should have the before and after images, and we can get the primary key from the before image for deletes and updates, and from the after image for inserts and updates if the PK might change).
The operation type.
The data (the row as a map of column names to values).
We must handle reorg events:
How do we identify a reorg event? This might be database-specific. For example, in DB2, a reorg might generate an update with a special flag? Or it might be an update that doesn't change any user columns?
We might need to look at the event and see if the before and after are the same except for a system-generated column (like RID). Alternatively, the CDC source might flag it.
If we detect a reorg event, we might treat it as a no-op for the user data, but if the primary key is a system-generated RID, then we must update the primary key in the target.
We must also handle the case where the primary key changes (if the source allows that). This is a special update that changes the primary key. We must update the target's primary key accordingly (which might be a delete+insert in some target systems that don't support primary key updates).
Writing to the target:
We need to convert the event into a target-specific operation (SQL or target API).
For idempotency and replay safety, we can use the offset (or a combination of table, primary key, and offset) to deduplicate at the target.
One way: We can store the last applied offset for each table (or partition) and only apply events with a higher offset. But note: offsets might not be globally comparable across partitions. So we might need to store the offset per partition and then when replaying, we must replay from the same partition.
Alternatively, we can make the target operation idempotent by using the primary key and the event's data. But if the event is an update, we can use the primary key to update the row. If the row has changed since the last event, then we are overwriting with the new value. This is the desired behavior.
code
We design the bridge for continuous replication with the following features:
code
11. Implementation considerations:
code
- We need to parse the CDC event's schema and data. We can use a library like Avro or JSON schema.
- We need to connect to the target database and execute SQL statements. We must handle errors and retries.
- We must handle backpressure and memory usage when buffering for global ordering.
- We must handle schema changes that occur while we are processing. For example, if a new column is added, we must alter the table before we process events that have that column.
- We must handle the case where the target table does not exist. We might need to create it? Or assume it exists.
- We must handle the case where the primary key is composite. Then our condition for update/delete must include all primary key columns.
- We must handle the case where the event does not have a primary key? Then we cannot apply it? We might need to use all columns as a key? That is not safe. So we assume every table has a primary key.
12. Conclusion:
code
I'll design a comprehensive CDC bridge that addresses your four key requirements. Here's an architecture that balances correctness, performance, and operational safety:
System Architecture Overview
code
Source DB → CDC Connector → Message Queue (Ordered) → Bridge Processor → Target System
↑ ↑
Schema Registry Metadata Store
Detection: Compare event schema_id with target table schema
Validation:
Backward compatibility check (new schema can read old data)
Forward compatibility check (old schema can read new data)
Actions:
Add column: ALTER TABLE ADD COLUMN IF NOT EXISTS
Drop column: Soft delete (mark as deprecated) first
Type change: Safe promotions only (INT → BIGINT, VARCHAR(100) → VARCHAR(200))
Rename column: Create new column, copy data, shadow old column
Data Conversion Layer
python
def convert_value(old_schema, new_schema, column_name, value):
"""Safely convert between schema versions"""
old_type = old_schema.fields[column_name].type
new_type = new_schema.fields[column_name].type
if is_compatible(old_type, new_type):
return value # No conversion needed
elif should_promote(old_type, new_type):
return promote_type(value, old_type, new_type)
else:
# Log warning, use default value or fail based on policy
return handle_incompatible(value, column_name)
3. Reorg (Reorganization) Handling
Detection Patterns
python
def detect_reorg(event):
"""Identify reorganization vs actual data change"""
indicators = {
'same_rowid_different_location': (
event.op == 'update' and
event.before['rowid'] != event.after['rowid'] and
all(event.before[k] == event.after[k]
for k in user_columns if k in event.before)
),
'ghost_cleanup': (
event.op == 'delete' and
event.before.get('is_ghost', False) and
not event.after
),
'page_split': (
event.op == 'update' and
event.before['ctid'] != event.after['ctid'] and
data_unchanged(event.before, event.after)
)
}
return any(indicators.values())
Handling Strategies
Filter reorg events: Completely skip if no user data changed
Update location metadata: If rowid/ctid changed for tracking
Batch mode: Buffer reorg events and flush as single no-op
Special handling for:
Index-organized tables: Maintain index structure separately
Partition moves: Update partition mapping tables
Online redefinitions: Use DBMS_REDEFINITION equivalents
4. Replay Safety
Idempotency Design
sql
-- Composite deduplication key
CREATE UNIQUE INDEX cdc_event_idempotency_idx
ON target_table (
source_table_name,
source_pk_hash,
source_commit_lsn,
source_offset
);
-- Alternatively: transactional outbox pattern
CREATE TABLE cdc_outbox (
id BIGSERIAL PRIMARY KEY,
event_id UUID, -- Source event UUID
status TEXT CHECK (status IN ('PENDING', 'PROCESSED', 'FAILED')),
processed_at TIMESTAMPTZ,
retry_count INT DEFAULT 0,
payload JSONB,
UNIQUE(event_id)
);
1. Pause CDC ingestion (optional)
2. Set target to read-only mode
3. Start replay from specific LSN/timestamp
4. Validate row counts/checksums
5. Resume normal operation
Gap detection and recovery:
sql
-- Find ordering gaps
SELECT table_name, partition,
MAX(lsn) - MIN(lsn) as lsn_range,
COUNT(*) as event_count
FROM cdc_metadata
GROUP BY table_name, partition
HAVING MAX(lsn) - MIN(lsn) != COUNT(*) - 1;
7. Limitations and Trade-offs
Requirement
Trade-off
Mitigation
Global ordering
Throughput impact (single thread)
Only when absolutely needed
Schema evolution
Potential data quality issues
Strict compatibility checks
Reorg handling
Might miss logical changes
Manual review process
Replay safety
Storage overhead (deduplication)
TTL-based cleanup
Key Design Principles
Observability first: Every decision tracked in metadata
Idempotency by design: Every operation can be safely retried
Graceful degradation: Schema violations logged, not fatal
Replay as first-class citizen: All state captured for replay
This design provides a robust foundation that can be adapted to specific database systems (PostgreSQL, MySQL, Oracle, etc.) and target systems (Snowflake, BigQuery, Redshift, etc.) while maintaining the four critical properties you specified.
However, if we are replaying, we might have already applied an update and then we apply it again. That would set the row to the same value (if the event is the same) but might have side effects (like updating a timestamp column). So it's better to avoid reapplying the same event.
Therefore, we need to track which events have been applied. We can do:
Option 1: Store the offset of the last applied event per table (or per partition). But note: if we have multiple partitions for a table, we must store the offset per partition. And when replaying, we might want to start from an earlier offset in one partition but continue in another? This becomes complex.
Option 2: Store the event's offset (or a hash of the event) in the target as a marker that it has been applied. Then for each event, we check if we have already applied it. This is heavy because we have to check every time.
Option 3: Rely on the target's transactionality and the fact that we are applying events in order. We can store the current state of the row (the latest version) and then when we apply an event, we check if the event's data is already the current state? But that doesn't work for deletes.
A better approach: use the CDC event's ts_ms and the primary key to determine if the event is already reflected in the target. But if we are replaying, the target might have a newer state.
Given the complexity, perhaps we should not try to make the bridge itself idempotent, but rather rely on the consumer group offsets (if using Kafka) and only commit the offset after the event is successfully written. Then, when replaying, we reset the offset to an earlier point and consume again. This will cause the same events to be processed again, so we must ensure that the target operations are idempotent.
How to make the target operations idempotent?
For inserts:
INSERT ... ON CONFLICT (primary_key) DO UPDATE SET ...
But note: if we are replaying an insert that was already applied, then the row exists and we update. But the update might set the same values? That's safe.
For updates:
UPDATE table SET ... WHERE primary_key = ? AND ?
But that condition would require knowing the previous state, which we don't have if we are replaying from the beginning.
Alternatively, we can use the CDC event's before and after to decide:
code
If the event is an update, we can do:
UPDATE table SET ... WHERE primary_key = ? AND <all columns before the update>
Then, if no row is updated, it means the current state is not the same as the before image, so we skip? But that might be because another event has already updated it. In that case, we should apply the update?
Actually, in a CDC stream, we expect that the events are applied in the same order as the source. So if we are replaying from the beginning, we should apply every event in order. But if we are starting from a later point (like after a failure) and we have already applied some events, then we must not apply them again.
Therefore, we must have a way to know which events have been applied. This brings us back to storing the offset.
Proposed solution:
We store in the target database (or in a separate metadata table) the following for each table/partition:
code
last_applied_offset (or a set of applied offsets, but that could be large)
Then, for each event, we check if the event's offset is greater than the last_applied_offset for that partition (and if the event's offset is exactly the next one, then we apply). But note: offsets might not be sequential (in Kafka, they are, but in other systems, they might not be). So we might store the maximum offset applied and then apply only if the event's offset is greater than that? But if we have multiple partitions, we might have to store per partition.
Alternatively, we can store the offset per table and then when we process an event, we check if the offset is higher than the stored one. But if we have multiple partitions, we might get events from different partitions and we must store the offset per partition.
Let's assume the CDC source provides a partition id (like Kafka partition) and an offset. We can store:
Then, for each event, we look up the metadata for the event's table and partition. If the event's offset is greater than the stored offset, we apply the event and update the metadata. If it is less or equal, we skip (because we already applied it or it's out of order? but we should get events in order per partition, so if we get an offset less than the stored one, it might be a replay of an old event, so we skip).
However, note: during normal operation, we expect offsets to increase. But if we restart the bridge and start from an earlier offset (for replay), we might get an event with an offset that is less than the current stored offset. In that case, we must reset the stored offset to the replay starting point? But then we would be missing events that were applied after the stored offset and before the replay start.
So the metadata table must be reset when we start a replay? That is error-prone.
Alternatively, we can not store the offset in the target, but rely on the CDC source's offset management (like Kafka consumer groups). Then, when we replay, we reset the consumer group offset. But then we must ensure that the target operations are idempotent because we will be reapplying events.
So we need idempotent operations in the target.
How to make the operations idempotent without storing offsets?
We can use the event's primary key and the event's data to decide:
code
For insert:
If the row exists, update it with the new values? But note: the insert event might have been followed by an update, so if we reapply the insert, we might overwrite a later update.
For update:
We can use a condition that the current row matches the before image. If it does, then we apply the update. If not, then we skip because the row has been updated by a later event (that we have already applied). But if we are replaying from the beginning, we expect that the row is in the before image state.
For delete:
If the row exists and matches the before image, delete it. Otherwise, skip.
But note: if we are replaying a sequence of events, we must apply them in order. So if we are at event N and we have already applied event N+1 (because we are replaying from an earlier point but we had already applied some events from a later point), then when we try to apply event N, the row state might not match the before image because event N+1 changed it. So we skip event N. But then we have a gap? Actually, we have already applied event N+1, so we don't need event N. But what if event N+1 was an update that depends on event N? In a CDC stream, events are independent in the sense that each event represents the state after the transaction. So if we apply event N+1, we are setting the row to the state after event N+1. Event N is the state after event N, which is overwritten by event N+1. So skipping event N is safe.
However, if we are replaying from the beginning, we must apply every event. So the condition method requires that we know the current state of the row in the target. We can get the current state by reading the target row? That would be expensive.
Given the complexity, perhaps the best approach is:
a. Use the CDC source's offset management (like Kafka consumer groups) to track progress. This works well for continuous processing.
b. For replay, we reset the consumer group offset to the desired point and then process events again. But then we must ensure that the target operations are idempotent.
c. To achieve idempotency, we design the target operations to be conditional on the event's before image (for updates and deletes) and on the absence of the row for inserts? But for inserts, if the row already exists, we might want to update it? That would be a no-op if the row is already in the desired state? Not necessarily: if the insert event is for a row that we have already inserted, but then updated, then reapplying the insert would set the row back to the initial state? That would be wrong.
So the conditional update/delete using the before image is safe because it only applies if the current state matches the before image (i.e., no later event has changed it). But for inserts, we don't have a before image. We can check if the row exists? If it exists, then we skip? But what if the row exists but with different values? That would mean that we have already applied a different insert? That should not happen because the primary key should be the same and the insert event is for a specific primary key. So if the row exists, it must be the same as the insert event? Not necessarily: if we are replaying and we have already applied an update, then the row exists but with updated values.
So for inserts, we can do:
code
INSERT INTO table (columns) VALUES (...)
ON CONFLICT (primary_key) DO NOTHING;
But note: if the row exists and the values are different, we leave the existing row (which might be from a later event). That is safe because we are replaying an old event and we already have a newer state.
However, if the row exists and the values are the same, then it's the same as the insert event, so we do nothing and that's safe.
But what if the row exists and the values are different? That means we have already applied a later event (an update) that changed the row. So we don't want to overwrite with the old insert. So DO NOTHING is safe.
But what if the row was deleted after the insert? Then the insert would try to insert again, which is safe because the row doesn't exist. But if we are replaying from the beginning and we have already applied the insert and then the delete, then when we replay the insert, the row doesn't exist (because we deleted it) and we insert again? That would be wrong because we are inserting a row that was deleted in the original sequence? Actually, in the original sequence, the insert was followed by a delete. So if we replay the insert and then the delete, we get the same final state (deleted). But if we only replay the insert (and not the delete) then we would have an extra row.
So we must replay the entire sequence from the beginning to maintain consistency. Therefore, when we reset the offset for replay, we must start from a point that is consistent (like a snapshot) and then replay all events from that point.
Given that, we can design:
code
For each event, we apply it conditionally:
Insert:
INSERT ... ON CONFLICT (primary_key) DO UPDATE SET ...
But that would update if there's a conflict, which we don't want because the existing row might be from a later event.
So we want to only insert if the row doesn't exist. So:
INSERT ... ON CONFLICT (primary_key) DO NOTHING.
Update:
UPDATE table SET ... WHERE primary_key = ? AND [all columns = before image]
If the row is updated (count>0), then we have applied the update. If not, then the current state doesn't match the before image, so we skip.
Delete:
DELETE FROM table WHERE primary_key = ? AND [all columns = before image]
If the row is deleted (count>0), then we have applied the delete. Otherwise, skip.
But note: for update and delete, we are comparing the entire before image. This requires that we know the current state of the row in the target. We can do that by including all columns in the condition. However, if the target table has columns that are not in the source, we might have to ignore those? Or we must include only the columns that are in the event.
Also, if the target table has columns that are not in the source, we cannot compare them. So we must only compare the columns that are present in the event.
But note: the event might not have all columns (if it's a partial update). In CDC, we usually have the before and after images. For an update, the before image has the old values for the columns that are in the event (and maybe others? but typically only the changed columns are in the after image, and the before image has the old values for the changed columns and possibly the primary key). So we might not have all columns in the event.
Therefore, we cannot compare the entire row. We must rely on the primary key and the fact that the event represents a change that happened at the source.
Given the limitations, perhaps we should not try to make the operations conditional on the entire row. Instead, we rely on the offset tracking and assume that we are applying events in order without gaps. Then we don't need conditional updates.
But if we are replaying from an earlier offset, we must have stored the state of the target at that offset? That is not feasible.
Conclusion for replay safety:
We must have a way to track which events have been applied. The most straightforward is to store the offset (per partition) in the target. Then, when processing an event, we check if the event's offset is greater than the stored offset for that partition. If yes, we apply and update the stored offset. If no, we skip.
But note: what if we have multiple partitions for the same table? We store the offset per partition. Then, when we replay, we reset the stored offset for each partition to the desired starting offset. But we must reset for all partitions? And what if we want to replay only one partition? That might be acceptable.
However, if we are using a system that does not have partitioned topics (or if we have a single partition per table) then it's simpler.
So the plan:
code
- For each event, we extract the table name, partition id (if applicable), and offset.
- We check the metadata table for that table and partition. If the event's offset is greater than the stored offset, we apply the event and update the stored offset to the event's offset.
- We must do this in a transaction: read the metadata, apply the event, update the metadata. But note: the event application might be an insert/update/delete that we want to commit separately? We can do:
BEGIN;
-- Apply the event (insert/update/delete)
-- Update the metadata table to set last_applied_offset = event.offset for the table and partition.
COMMIT;
- This ensures that if the transaction fails, we don't update the metadata and we can retry.
- But what if we have multiple events in the same transaction? We might want to batch them. Then we can update the metadata to the maximum offset in the batch.
This approach requires that the target database supports transactions and that we can store the metadata in the same database (or a separate one with transactional guarantees).
Also, note that the offset must be comparable (numeric) and monotonic per partition.
Putting it all together:
Steps for the bridge:
a. Setup:
- Create the metadata table in the target database.
b. Consume events from the CDC source (in order per partition).
c. For each event (or batch of events):
- Extract table name, partition id (if available), offset, operation, and row data.
- Look up the current last_applied_offset for the table and partition from the metadata table.
- If the event's offset > last_applied_offset, then:
- Apply the event to the target table (using INSERT/UPDATE/DELETE).
- Update the metadata table to set last_applied_offset = event.offset (or the maximum offset in the batch) for that table and partition.
- Else, skip the event.
d. Commit the transaction (if we are doing per-event transactions) or batch the events and update the metadata at the end of the batch.
e. For schema evolution: we must alter the target table if the source schema changes. We can do:
code
- When we encounter a new column (that doesn't exist in the target), we alter the target table to add the column.
- When a column is dropped in the source, we might leave it in the target or drop it? We must decide. Also, note that old events might have that column. We must handle events that have columns that don't exist in the current target schema? We can ignore them? But if we are replaying, we might need the old data?
- We can store the data in a JSON column if we want to keep all historical columns? Or we can alter the table to add the column and then later drop it? But then we lose the data in that column for old rows? Actually, if we drop the column, then the old rows will have NULL for that column? But if we are storing the entire history, we might want to keep the old values?
- This is a complex problem. One approach is to use a schema-on-read storage (like a data lake) and then we don't alter the table, but just store the events as they are. Then the reader must handle the schema evolution.
- If we are writing to a relational database, we might need to:
Option 1: Never drop columns, only add. Then we keep all historical data. But the table might become very wide.
Option 2: When a column is dropped in the source, we also drop it in the target after a certain period (after we are sure we don't need old data). But then when we replay old events that have the dropped column, we will get an error because the column doesn't exist.
- So we must decide: do we want to keep the full history with all columns that ever existed? Or do we want to mirror the current source schema?
- Given that CDC is often used for auditing and replay, we might want to keep all columns that ever existed. Therefore, we should only add columns and never drop. Then, when we get an event that has a column we haven't seen before, we add it. But note: if we add a column, then old rows will have NULL for that column, which is acceptable.
- However, if the source drops a column and then adds a column with the same name but a different type, we might have a conflict. We must handle type changes as well.
- This suggests that we might need a more sophisticated schema management. We might store the schema of each event and then have a way to map the event's schema to the current target table. But that is very complex.
- Given the complexity, perhaps we should use a format that stores the entire row as a JSON document (or similar) in the target. Then we don't have to alter the table for every schema change. We can have a table with:
id (primary key),
data (JSON),
operation,
offset,
table_name,
event_time,
etc.
- Then we don't have to worry about schema evolution because we store the entire event as a JSON document. But then querying becomes harder and we lose the relational structure.
- Alternatively, we can use a hybrid: store the current state in a relational table and also store the CDC events in a separate audit table. Then we update the current state table by applying the events, and the audit table stores every event with its full data. Then we can replay from the audit table if needed.
- But the requirement is for a bridge that writes to a target. The target might be a relational database and we want to maintain the current state. So we must alter the table to match the source schema.
- Given the time, we might assume that the source schema only evolves by adding columns and never by dropping or changing types. Then we can:
- When we get an event with a column that doesn't exist in the target table, we add the column (with a type that can be inferred from the event data?).
- We must be cautious: if the column already exists but with a different type, we might need to alter the type? That could break existing data.
- So we must have a way to handle type changes? This is very database-specific and complex.
Given the complexity of schema evolution, we might limit the scope to:
code
- Only add columns (if the source adds a column, we add it in the target).
- Never drop columns (so we keep all columns that ever existed).
- For type changes, we might try to alter the column type if the new type is compatible? But that is risky.
Alternatively, we can store the row as a JSON document in a column and then use a view to project the current schema? That way, we don't have to alter the table. But then we lose the ability to have constraints and indexes on individual columns.
Reorg handling:
We must detect reorg events and handle them appropriately.
How to detect?
Some CDC sources might mark them. For example, Debezium has an __debezium.source field that might indicate a reorg? Or we might look at the before and after images: if they are the same for all user columns, then it might be a reorg that only changed a system column (like RID).
We can check: if the operation is an update and the before and after are the same for all non-system columns, then it's a reorg.
But note: a normal update might change a column to the same value? That's unlikely but possible.
Alternatively, the database might have a flag in the CDC event. For example, in DB2, a reorg might be represented as an update with a special flag in the log. We must check the documentation of the CDC source.
Once we detect a reorg event:
If the reorg changes the primary key (for example, the ROWID changes), then we must update the primary key in the target. This is essentially an update of the primary key. We can do:
UPDATE table SET primary_key_column = new_value WHERE primary_key_column = old_value;
But note: if the primary key is the same in the before and after, then it's just a no-op for the user data.
If the primary key doesn't change, then we don't need to do anything because the row is the same.
However, note that in some databases, the reorg might change the primary key if the primary key is a ROWID. So we must update the primary key. But then we must be cautious because the primary key might be referenced by foreign keys. So we might need to update foreign keys as well? That is complex.
Given the complexity, perhaps we assume that the primary key is not a system-generated ROWID and does not change during reorg. Then we can ignore reorg events that don't change user columns.
But if the primary key is a ROWID and it changes, then we must update the primary key and all foreign keys. This might be too heavy for the bridge.
Therefore, we might assume that the source database's CDC events for reorg will not change the primary key (if the primary key is a user-defined key). If the primary key is a system-generated ROWID, then we might not be able to handle it easily.
We might need to design the bridge to handle ROWID changes by treating the reorg as a delete+insert? But that would break foreign keys.
Given the constraints, we might state that the bridge does not support tables with ROWID as the primary key that can change during reorg. Or we require that the source database's CDC events for reorg include the new ROWID and the old ROWID, and we update the primary key and all foreign keys accordingly. But that requires knowing the foreign key relationships.
This is very complex. So for simplicity, we assume that the primary key is user-defined and does not change during reorg. Then, for reorg events, we can ignore them if the user columns are the same. If the user columns change, then it's a normal update.
Ordering across partitions:
If the target requires global ordering (across partitions), we might need to have a single thread that processes events from all partitions in the order of the source's commit timestamp (if available). But note: the CDC events might not have a global commit timestamp? They might have a transaction commit time, but two transactions from different partitions might commit at the same time.
We can use the event's ts_ms (if available) and then order by that. But if two events have the same ts_ms, we might need a tie-breaker (like offset). However, the source's order of commit might not be exactly the same as the ts_ms if the clock is not perfectly synchronized.
Alternatively, we can rely on the CDC source's ordering: if the source database has a global transaction log, then the events are in the order of commit. But if we are reading from Kafka, each partition is ordered, but not across partitions.
Therefore, if we need global ordering, we must:
Consume from all partitions.
Buffer events and sort by a global ordering key (like the source's commit LSN or a combination of commit timestamp and transaction ID).
Then process in that order.
This buffering might cause delays and requires memory. Also, we must have a way to know when we have received all events for a given commit timestamp? Not trivial.
Given the complexity, we might assume that per-partition ordering is sufficient. Many targets (like data warehouses) can handle out-of-order events per partition if they are for different keys? But if we are updating the same row from multiple partitions (which shouldn't happen if the row is in one partition) then we must order.
So we assume that the source table is partitioned and each row belongs to one partition. Then events for a given row are in the same partition and we have per-row ordering.
If the source table is not partitioned, then we might have multiple partitions for the same table (for load balancing) and then we must merge the streams and sort by offset? But the offset in Kafka is per partition and not globally comparable.
Therefore, we might require that the CDC source provides a globally monotonically increasing offset (like a transaction log sequence number) that we can use to order across partitions.
Let's assume the CDC event has a field source.lsn (log sequence number) that is globally increasing. Then we can sort by lsn across partitions.
But note: the CDC source might not provide that. Debezium, for example, provides source.lsn for databases that have LSN (like PostgreSQL). But for MySQL, it provides source.file and source.pos which are not globally comparable across files.
So we might have to rely on the source's transaction ID and the offset within the transaction?
Given the variety of CDC sources, we might design the bridge to be configurable:
We can specify a set of fields to use for global ordering (like ts_ms and offset). But note: ts_ms might have duplicates.
We can use the following for global ordering:
First by ts_ms (if available), then by source.lsn (if available), then by partition and offset (as a last resort).
But if we don't have ts_ms or lsn, we cannot guarantee global ordering.
We might decide that the bridge does not guarantee global ordering unless the source provides a global ordering field.
For the design, we will assume that we are only required to maintain per-partition ordering, and that the target can handle out-of-order events from different partitions (or that the source table is partitioned and each row is in one partition).
Summary of the design:
We assume the CDC source provides events with:
table,
partition (optional, if not provided we assume one partition per table?),
offset (monotonic per partition),
operation (c, u, d, r),
before and after (or just after for insert, just before for delete),
and optionally:
ts_ms (timestamp of the event),
lsn (log sequence number, if available and globally comparable).
We have a metadata table in the target to store the last applied offset per table and partition.
We process events in the order they are received per partition. If global ordering is required and the source provides a global ordering field, we buffer and sort by that field.
For each event:
Step 1: Check the metadata for the table and partition. If the event's offset is <= the stored offset, skip.
Step 2: Handle schema evolution:
code
- Compare the event's schema (the set of columns in the before/after) with the target table's columns.
- For any new column (not in the target table), add it to the target table (with a type that can be inferred from the event data, or we must have a mapping?).
- We assume that the target table's column types are compatible with the source. We might need to convert types? This is a separate problem.
Step 3: Handle reorg:
code
- If the operation is update and the before and after are the same for all non-system columns, then it's a reorg.
- If the primary key is a system-generated ROWID and it changed, then we update the primary key (and all foreign keys? we might not have that information, so we might fail). We assume the primary key is user-defined and does not change.
Step 4: Apply the event:
code
- For insert (c):
INSERT INTO table (columns) VALUES (values)
ON CONFLICT (primary_key) DO NOTHING;
- For update (u):
UPDATE table SET column1 = value1, ...
WHERE primary_key = ?
AND [all columns in the before image equal the current values in the target]
But note: the before image might not have all columns. We can only condition on the columns that are in the before image? And we must have the primary key.
Alternatively, we can use the offset tracking and assume that we are applying in order without gaps, so we don't need the condition? But then if we are replaying from an earlier offset, we might have already applied a later event and the condition would fail?
Actually, with the offset tracking, we are only applying events that are after the last applied offset. So if we are replaying, we reset the stored offset to an earlier value, and then we will apply events that we might have already applied (if we had applied them before and then reset). So we need the condition to avoid overwriting a later state.
- Therefore, we must use the condition for updates and deletes.
- How to build the condition? We have the before image (a map of column names to values). We can build a WHERE clause that checks the primary key and all columns in the before image. But note: the before image might have a subset of columns (if it's a partial update). We can only condition on the columns that are in the before image.
- Example:
UPDATE table SET col1 = new_val1, col2 = new_val2
WHERE primary_key = ?
AND col1 = old_val1
AND col2 = old_val2
AND ... (for all columns in the before image)
- If the before image does not have a column, we cannot condition on it. But that's okay because if the column is not in the before image, then it wasn't changed by this event, so we don't care about its current value? Actually, we want to make sure that the row is exactly in the state before the update. If a column is not in the before image, we don't know its value in the before state? But in CDC, the before image usually contains the entire row? It depends on the CDC source and the logging mode.
- In row-based logging (like MySQL ROW or PostgreSQL logical decoding), the before image is the entire row. So we have all columns. In statement-based logging, we might not. So we must know the CDC source.
- We assume the CDC source provides the entire before image for updates and deletes, and the entire after image for inserts and updates.
Step 5: Update the metadata table with the event's offset.
We do steps 1-5 in a transaction.
Challenges:
Type mapping between source and target: we might need to convert data types. We can use a mapping table or rely on the target database's implicit conversion? But that might fail.
Handling of non-atomic events: if the event is part of a multi-table transaction, we might have events for multiple tables. We are processing per event, so we might break atomicity. But that's acceptable because we are applying CDC events in the order they were committed, and each event is a change to a single table. The target might not have the same transaction boundaries.
If the source uses a transaction that updates multiple tables, we will get multiple events (one per table) in the same order. We will apply them in separate transactions (if we do per-event transactions). This might leave the target in an inconsistent state if one event fails? But note: the source committed, so we should try to apply all. We might need to batch events from the same transaction? But how do we know the transaction boundaries? The CDC event might have a transaction ID. We can batch events with the same transaction ID and apply them in a single transaction? But then we might have events for multiple tables and we must have the tables in the same database? If the target is a single database, we can do that. But if the target is multiple databases, we cannot.
Given the complexity, we might apply each event in its own transaction. If an event fails, we can retry. But if we are in the middle of a multi-table transaction and one event fails, then the target will be inconsistent? Yes. So we must either:
a. Apply all events of a transaction in a single transaction (if they are in the same database) and rollback if any fails.
b. Or, we must have compensating transactions to undo the applied events if a subsequent event fails. This is complex.
We might decide that the bridge does not guarantee atomicity across tables. We apply each event independently. If an event fails, we retry until it succeeds (or dead-letter). This might leave the target in an inconsistent state if the source transaction updated multiple tables and one of them fails.
To mitigate, we can:
Buffer events until we have the entire transaction? But we don't know the transaction boundaries until we see the transaction commit event? Some CDC sources provide a transaction boundary marker (like a "transaction" event in Debezium). We can wait for the transaction commit and then apply all events in the transaction in a single transaction? But that would increase latency.
Alternatively, we can apply events in the order they come and if one fails, we stop and wait for manual intervention? Not ideal.
Given the time, we might assume that each event is independent and that the source's transaction boundaries are not critical for the target. Or we might require that the source's transactions are single-table? That is not realistic.
Another idea: we can use the transaction ID to group events and then apply them in a single transaction if they are for the same target database. But if the target is a single database, we can do:
code
For each transaction (identified by transaction_id), we buffer all events until we see the transaction commit (or until we timeout). Then we apply them in a single transaction.
But note: the CDC stream might not have a clear transaction commit event. Some sources provide a "transaction" event that marks the beginning and end? Debezium provides a source.sequence and source.offset that can be used to determine the transaction boundaries? It's complicated.
Given the complexity, we might decide to not handle multi-table transactions atomically. We apply each event individually and if one fails, we retry. We accept that the target might be temporarily inconsistent until all events of a transaction are applied.
For many use cases (like analytics), this is acceptable because we are eventually consistent.
Conclusion:
We design a bridge that:
Reads from a CDC source (Kafka topic, etc.) and maintains per-partition ordering.
Tracks the last applied offset per table and partition in a metadata table in the target database.
Applies events only if the event's offset is greater than the stored offset for that partition.
Handles schema evolution by adding new columns (but not dropping or changing types) to the target table.
Handles reorg events by ignoring them if they don't change user columns, or by updating the primary key if it's a user-defined key and it changes (rare).
Applies events conditionally (using the before image) to be idempotent, but we also rely on offset tracking to avoid reapplying events.
However, the conditional update/delete using the before image is necessary for replay safety when we reset the offset and replay old events that might have been already applied in a different order? But with offset tracking, we are only applying events that are after the stored offset. So if we reset the stored offset to an earlier value, we will reapply events that we might have applied before. The condition using the before image will prevent us from overwriting a newer state.
So we do:
code
For update:
UPDATE table SET ...
WHERE primary_key = ?
AND [for each column in the before image: column = before_value]
For delete:
DELETE FROM table
WHERE primary_key = ?
AND [for each column in the before image: column = before_value]
And for insert, we use ON CONFLICT DO NOTHING.
This makes the operations idempotent in the sense that if we apply the same event twice, the second time it will have no effect (because the row state will not match the before image for update/delete, and for insert the row will already exist).
But note: if we are replaying a sequence of events, we might apply an event that changes the row, and then later apply an older event that tries to update the row to an older state? That would be wrong because we already applied a newer event. But with the condition, the older event's update will fail because the row is not in the before image state (it's in a newer state). So we skip the older event. This is safe because the newer event has already set the row to a state that is after the older event.
However, if we are replaying from the beginning, we want to apply every event in order. So we must reset the stored offset to the beginning and then apply all events. The condition will not skip any event because the row will be in the expected state (since we are applying in order).
But what if we have two events for the same row:
code
Event 1: update col1 from A to B.
Event 2: update col2 from X to Y.
If we apply event1 and then event2, that's correct.
If we replay from the beginning, we will apply event1 and then event2.
If we reset the offset to after event1 and then replay event2, then when we apply event2, the row's col2 should be X (because we didn't apply event1? But we reset the offset after event1, so we have already applied event1? Actually, we reset the stored offset to a value that is less than event2, so we will apply event2. But the row's col2 might be X (if we haven't applied event1? Wait, we reset the offset to a point before event2, but we might have already applied event1 and event2?
Let's clarify:
code
We have applied events up to offset 100 (which includes event1 and event2). Then we reset the stored offset for that partition to 50 (which is before event1). Then we start consuming from offset 50. We will see event1 (offset 60) and event2 (offset 70).
When we see event1 (offset 60), we check the stored offset (50) and since 60>50, we apply event1. Then we update the stored offset to 60.
Then we see event2 (offset 70), stored offset is 60, so we apply event2 and update to 70.
Now, what if we had already applied event1 and event2 before the reset? Then when we apply event1 again, the row state will not match the before image (because we already applied event2? Actually, after event2, the row's col1 is B and col2 is Y. The before image for event1 is col1=A, col2=X. So when we try to apply event1, the condition (col1=A AND col2=X) will fail because col1 is B and col2 is Y. So we skip event1. Then when we try event2, the condition (col1=B AND col2=X) will fail because col2 is Y? Wait, after event1 (if we had applied it) the row is col1=B, col2=X. Then event2 changes col2 to Y. So the before image for event2 is col1=B, col2=X. But after event1 (which we skipped) the row is still col1=A, col2=X? Actually, we skipped event1, so the row is in the state after event2? That's inconsistent.
This shows that if we reset the offset to a point before an event that we have already applied (and then applied a later event that depends on it), we cannot replay the earlier event because the row state is not the before image.
Therefore, we must not reset the offset to a point that is before an event that has been applied and then a later event that depends on it. In other words, we must reset to a point that is a consistent snapshot.
How to get a consistent snapshot? We must reset to a point where the target state matches the source state at that offset. That is only possible if we have stored the state of the target at that offset? We don't.
So the offset reset for replay is only safe if we are starting from a point that is after the last event we applied? That doesn't make sense for replay.
Actually, for replay we want to start from an earlier point and reapply all events from that point. But we must have a clean state at that point. So we must:
- Either truncate the target table and reset the metadata offset, then replay from the beginning? That would work if we are allowed to lose the current state.
- Or we must have a way to restore the target to the state at the replay starting point. That might require having a snapshot of the target at that point.
Given the complexity, we might state that the bridge does not support replay from an arbitrary point unless we are starting from a fresh target (or we have a snapshot of the target at the replay start point).
Alternatively, we can design the bridge to be used only for continuous replication, and for replay we use a separate process that restores from a backup and then replays from the beginning.
Therefore, we might remove the offset tracking for replay and instead rely on the fact that we are applying events in order and we never skip an event (we always apply if the offset is greater than the stored offset). Then, for replay, we must:
Step 1: Restore the target to the state at the replay start point (by restoring from a backup that corresponds to that point in the CDC log).
Step 2: Reset the stored offset in the metadata table to the replay start offset.
Step 3: Start consuming from the replay start offset and apply events.
Then, because we restored the target to the state at the start point, the before images will match for every event.
So the bridge is safe for replay only if we restore the target to the correct state before resetting the offset.
Final design:
- Ordering: per-partition ordering (or global ordering if the source provides a global ordering field and we buffer and sort).
- Schema evolution: automatically add new columns (but not drop or change types). We assume that the target's column types are compatible with the source's data.
- Reorg handling: ignore reorg events that don't change user columns. If the primary key is a user-defined key and changes, update the primary key. We do not handle ROWID changes that require foreign key updates (we assume no foreign keys or that the primary key is not a ROWID).
- Replay safety: we track the last applied offset per table and partition. For replay, we require that the target is restored to the state at the replay start offset before resetting the metadata. Then we reset the stored offset to the replay start offset and start consuming from there.
Steps:
1. Initialize: create the metadata table.
2. For each event (or batch of events from the same partition):
a. Check the metadata for the table and partition. If the event's offset <= stored offset, skip.
b. If the event's offset > stored offset:
i. Check if the target table has all the columns in the event (from before/after). If not, add the missing columns (with a type that can be inferred from the event data? We might need a mapping configuration).
ii. If the operation is update and the before and after are the same for all non-system columns, and the primary key is the same, then skip (reorg with no user data change).
iii. If the operation is update and the primary key changed (and it's a user-defined primary key), then we update the primary key (and all foreign keys? We might not have foreign key info, so we might fail). We assume that the primary key is not a foreign key and there are no foreign keys referencing it? That's not realistic. So we might not support primary key changes.
iv. Apply the event:
- Insert (c):
INSERT INTO table (columns) VALUES (values)
ON CONFLICT (primary_key) DO NOTHING;
- Update (u):
UPDATE table SET col1 = new_val1, ...
WHERE primary_key = ?
AND [for each column in the before image: column = before_value]
- Delete (d):
DELETE FROM table
WHERE primary_key = ?
AND [for each column in the before image: column = before_value]
v. Update the metadata table to set last_applied_offset = event.offset (or the maximum offset in the batch) for the table and partition.
c. Commit the transaction.
Note: We assume that the CDC event provides the entire before image for updates and deletes, and the entire after image for inserts and updates.
We also assume that the primary key is known and does not change (except in the rare case of a user-defined primary key change, which we handle by updating the primary key column).
For global ordering, if required, we buffer events from all partitions and sort by a global ordering field (like lsn) and then process in that order. But note: the metadata table must then be updated per partition? Actually, if we sort globally, we are processing events out of partition order. Then we cannot use the partition-specific offset tracking? We might need to track the global offset? But the global offset might not be provided per event.
Given the complexity, we might not support global ordering and instead rely on the target to handle out-of-order events from different partitions (if the rows are independent). If the target requires global ordering for correctness (like for accounting where the order of transactions matters), then we must have a global ordering.
We might design the bridge to be configurable:
- If the source provides a global ordering field (like lsn), then we use that to order events across partitions and then process them in that order. We still track the offset per partition? Actually, if we are processing globally, we are breaking the per-partition order. But we are still applying events in the global order. We can still track the last applied offset per partition, but we might apply an event from partition B before an event from partition A that has a lower offset but a higher lsn? That's okay because we are following the global order.
- However, the metadata table's offset per partition might not be the latest offset from that partition because we are processing out-of-order? We must update the metadata for a partition when we apply an event from that partition. But if we apply an event from partition B with a high offset before an event from partition A with a lower offset, then the stored offset for partition B will be high, and for partition A will be low. That's acceptable because we are processing in global order, not per-partition order.
- But note: the CDC source might guarantee that within a partition, the offset order is the same as the lsn order? Probably yes. So if we process by global lsn, we will process events from each partition in offset order? Not necessarily: if we have two events from partition A with lsn 100 and 200, and one event from partition B with lsn 150, then we process A100, then B150, then A200. So for partition A, we processed offset of 100 and then 200, which is in order. So it's okay.
- Therefore, we can do:
Buffer events until we have at least one event from each partition? Not necessary. We can sort by lsn and then process as we have events. But we must ensure that we don't process an event with a higher lsn from a partition if there is an event with a lower lsn from the same partition that hasn't arrived yet? That could happen if the events are arriving out of order by lsn? But the CDC source should send events in lsn order? Not necessarily if we have multiple partitions and the lsn is not per-partition.
- Actually, if the lsn is global and increasing, then events with lower lsn should arrive before events with higher lsn. But network delays might cause out-of-order arrival? We can buffer until we are sure we have all events with lsn less than the current? That is the same as handling out-of-order events in a stream.
- Given the complexity, we might decide to not support global ordering unless we can guarantee that the events are delivered in global order (which is not typical for distributed systems).
Given the time, we will stick to per-partition ordering and assume that the target can handle out-of-order events from different partitions (or that the source table is partitioned and each row is in one partition).
This is a complex problem and we have made many assumptions. The design above is a starting point and would need to be adjusted based on the specific CDC source and target.
Given the time, we provide a high-level design and note the assumptions and limitations.
We can summarize the steps in pseudocode:
// Assume we have a function to get the next event from the CDC stream (per partition)
// and we have a connection to the target database.
// We have a metadata table: cdc_bridge_metadata(table_name, partition_id, last_applied_offset)
while (true) {
event = consume_event(); // from a specific partition
// Check if we should apply this event
metadata = query("SELECT last_applied_offset FROM cdc_bridge_metadata WHERE table_name = ? AND partition_id = ?",
event.table, event.partition);
if (metadata && event.offset <= metadata.last_applied_offset) {
continue; // skip
}
// Begin transaction
try {
// Step 1: Ensure table exists and has the required columns
ensure_table_columns(event.table, event.before, event.after);
// Step 2: Handle reorg (if update and no user column change and primary key same)
if (event.op == 'u' && is_reorg(event)) {
// If primary key changed, update primary key
if (primary_key_changed(event)) {
update_primary_key(event.table, event.before, event.after);
}
// Skip applying the update because the user data didn't change
// But note: if we updated the primary key, we already did it.
// If we didn't update the primary key, then we skip.
if (!primary_key_changed(event)) {
// Skip the update
// But we still need to update the metadata?
// We treat the reorg as an event that we have processed (so we update the metadata) but don't change user data.
// So we update the metadata and skip the update.
update_metadata(event.table, event.partition, event.offset);
commit();
continue;
}
}
// Step 3: Apply the event
switch (event.op) {
case 'c':
apply_insert(event.table, event.after);
break;
case 'u':
apply_update(event.table, event.before, event.after);
break;
case 'd':
apply_delete(event.table, event.before);
break;
case 'r': // snapshot
// We might ignore snapshot events if we are doing continuous replication?
// Or we might use them to initialize the target.
break;
}
// Step 4: Update metadata
update_metadata(event.table, event.partition, event.offset);
commit();
} catch (Exception e) {
rollback();
// handle error (retry, dead-letter, etc.)
}
}
The functions:
ensure_table_columns(table, before, after):
- Get the current columns of the table.
- Compare with the keys of the before and after maps (union of columns).
- For any missing column, add it with a type that we can infer from the data? Or we might have a type mapping configuration.
is_reorg(event):
- Check if the operation is update.
- Compare the before and after for all columns that are not system columns (we might have a list of system columns to ignore, like ROWID, etc.).
- If all non-system columns are equal, then it's a reorg.
primary_key_changed(event):
- Compare the primary key columns in the before and after. If any differ, return true.
update_primary_key(table, before, after):
- We need to update the primary key column(s) from the before value to the after value.
- But note: the primary key might be referenced by foreign keys. We might need to update the foreign keys as well? We don't have that information.
- So we might fail if there are foreign keys. Alternatively, we can disable foreign key checks, update, and then re-enable? But that might break referential integrity.
apply_insert(table, after):
- Build an INSERT statement with the columns and values from the after map.
- Add ON CONFLICT (primary_key) DO NOTHING.
apply_update(table, before, after):
- Build an UPDATE statement that sets the columns from the after map (excluding the primary key? Actually, the primary key might change, so we should include it? But we cannot update the primary key in the SET clause if it's the primary key? We can, but then we must update the primary key in the WHERE clause? Actually, we are updating the primary key? Then we must change the primary key value. But note: the WHERE clause uses the primary key from the before image. So we are updating the row with the old primary key to set the new primary key? That is allowed in some databases? In PostgreSQL, you can update the primary key.
- So we do:
UPDATE table
SET col1 = new_val1, col2 = new_val2, ... (all columns in the after map, including the primary key if it changed)
WHERE primary_key = old_primary_key_value
AND [for each column in the before image: column = before_value]
- But note: if the primary key changed, then the SET clause will set the primary key to the new value. That is acceptable.
- However, if there are foreign keys referencing this table, updating the primary key might break them. We might need to update the foreign keys in the referencing tables. We don't have that information.
- So we might not support primary key updates if there are foreign keys. We might assume no foreign keys or that the primary key is not changed.
apply_delete(table, before):
- DELETE FROM table
WHERE primary_key = ?
AND [for each column in the before image: column = before_value]
This design is complex and has many edge cases. It is meant as a starting point and would require extensive testing and adjustment for a specific use case.
Given the time, we cannot cover every possible scenario, but we have addressed the main requirements: ordering, schema evolution, reorg handling, and replay safety (with the caveat of requiring a restore for replay).
We hope this design is helpful.</think>