Skip to content

Commit 7f13257

Browse files
authored
Update optimization guidelines for CockroachDB SQL
Added recommendations for efficient SQL practices and alternatives to XA/Prepared Transactions.
1 parent 1946c05 commit 7f13257

1 file changed

Lines changed: 20 additions & 1 deletion

File tree

  • skills/query-and-schema-design/cockroachdb-sql/references/cockroachdb-rules

skills/query-and-schema-design/cockroachdb-sql/references/cockroachdb-rules/04-optimization.md

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,11 @@ SELECT * FROM large_table; -- ❌ Specify columns
9393

9494
-- Large OFFSET pagination
9595
SELECT * FROM table LIMIT 20 OFFSET 10000; -- ❌ Inefficient
96+
97+
-- XA / Prepared Transactions (not fully supported)
98+
PREPARE TRANSACTION 'tx_id'; -- ❌ Can cause stuck transactions and row locks
99+
COMMIT PREPARED 'tx_id'; -- ❌ Not fully supported, undocumented
100+
ROLLBACK PREPARED 'tx_id'; -- ❌ Use outbox pattern for cross-DB writes instead
96101
```
97102

98103
### DO Use These Instead
@@ -109,6 +114,20 @@ SELECT * FROM posts
109114
WHERE (created_at, id) < ($1, $2)
110115
ORDER BY created_at DESC, id DESC
111116
LIMIT 20; --
117+
118+
-- For cross-database consistency instead of XA/Prepared Transaction, use the Outbox pattern:
119+
--- 1. Write both the business data and an outbox event in one CockroachDB transaction
120+
BEGIN;
121+
INSERT INTO orders (id, user_id, total) VALUES ($1, $2, $3);
122+
INSERT INTO outbox_events (id, aggregate_id, event_type, payload)
123+
VALUES (gen_random_uuid(), $1, 'order_created', $4::JSONB);
124+
COMMIT; --- ✅
125+
126+
--- 2. Use a changefeed to deliver outbox events to the external system (e.g. Kafka → MongoDB)
127+
CREATE CHANGEFEED FOR TABLE outbox_events
128+
INTO 'kafka://broker:9092'
129+
WITH format = 'json', updated, resolved = '10s'; --- ✅
130+
112131
```
113132

114133
## Performance Best Practices
@@ -190,4 +209,4 @@ SELECT * FROM crdb_internal.ranges;
190209

191210
-- Check replication status
192211
SHOW RANGES FROM TABLE table_name;
193-
```
212+
```

0 commit comments

Comments
 (0)