Audit Cross Room Queries Before Moving D1 to DO
In this article
This guide walks you through auditing your Cloudflare D1 cross-room queries before migrating data to Durable Objects. You'll learn how to identify queries that span multiple rooms (or namespaces), assess their impact on consistency and performance, and refactor them for a DO-based architecture. This ensures your migration avoids data integrity issues and latency spikes.
What You'll Need
- Access to your Cloudflare account with D1 and Durable Objects enabled.
- A list of all your D1 database queries (from code, logs, or query inspector).
- Familiarity with your data model: know which tables or records belong to which room.
- A staging environment to test changes without affecting production.
- Basic understanding of JavaScript/TypeScript and the Workers runtime.
Step-by-Step
- Map your rooms to D1 tables or key prefixes. In D1, rooms are often represented by a
room_idcolumn or a key prefix likeroom:{id}:.... Document every table and query that references a room. - Collect all SQL queries. Search your codebase for
prepare(),bind(), andrun()calls. Also check the Cloudflare dashboard's D1 console for recent queries. Compile them into a spreadsheet or document. - Classify each query as single-room or cross-room. A single-room query has a WHERE clause that filters by
room_id(or equivalent). A cross-room query either has no room filter, joins multiple rooms, or uses subqueries that span rooms. Mark each query accordingly. - For each cross-room query, determine the business purpose. Ask: Does this query need to see data across all rooms (e.g., admin dashboard), or is it accidentally missing a room filter? If it's accidental, fix it to be single-room.
- Assess consistency requirements. For queries that legitimately span rooms, decide if they need strong consistency (e.g., leaderboard totals) or if eventual consistency is acceptable (e.g., analytics summaries). Durable Objects provide strong consistency per object, but cross-object queries are eventually consistent.
- Refactor cross-room queries for Durable Objects. In the DO model, each room becomes a Durable Object (or a set of objects). Cross-room queries must be replaced with:
- Fan-out: Call each room's DO to get its portion, then aggregate in the Worker.
- Materialized views: Maintain a separate DO or D1 table that stores aggregated data, updated asynchronously.
- Batch processing: Use a scheduled Worker to compute cross-room results and store them. - Rewrite the queries in code. For each cross-room query, replace the SQL with the appropriate DO call(s). For example, instead of
SELECT SUM(value) FROM scores WHERE room_id IN (...), call each room's DO methodgetSum()and add the results. - Test in staging. Run your refactored code against a staging D1 and DO setup. Compare results with the old D1 queries for a sample of rooms. Ensure the numbers match within your consistency tolerance.
- Monitor performance. Measure the latency of the new fan-out calls. If a cross-room query touches hundreds of rooms, it may be too slow. Consider caching or pre-aggregation.
- Plan the migration. Move data room by room. For each room, export its D1 rows, import into the DO's storage, and switch the code path. Verify the room works in isolation before moving the next.
- Decommission the old cross-room queries. After all rooms are migrated, remove the old SQL code and D1 tables that are no longer needed. Keep a backup for rollback.
Common Mistakes
- Assuming all queries are single-room. Some queries may use
room_idin a JOIN condition but still return data from multiple rooms. Always check the result set. - Ignoring transactions. D1 supports transactions across rooms; DOs do not. If you have a cross-room transaction, you must redesign it (e.g., using sagas or compensation).
- Over-fanning out. Calling hundreds of DOs per request can cause latency and cost issues. Use aggregation or caching.
- Forgetting about ordering. When aggregating from multiple DOs, the order of results may vary. Sort explicitly if needed.
- Not handling partial failures. If one DO call fails, your cross-room query may return incomplete data. Implement retries or fallback logic.
Tips
- Use a naming convention. Prefix all DO storage keys with the room ID to make it clear which data belongs where.
- Log all queries. In production, log every D1 query with its room_id. This helps you audit later.
- Start with read-only cross-room queries. Migrate those first, as they are easier to refactor. Handle writes later.
- Consider a hybrid approach. You don't have to move everything to DOs. Keep D1 for global data (users, settings) and use DOs for per-room data.
- Use the D1 query inspector. Cloudflare's dashboard shows recent queries; use it to catch queries you might have missed.
Troubleshooting
Missing queries in your audit. If you find a cross-room query after migration, it will likely break or return wrong data. To prevent this, add a runtime check: before executing any SQL, assert that a room_id filter is present (for single-room tables). If not, throw an error.
Latency spikes. If fan-out is slow, consider batching: instead of calling each DO individually, use Promise.all in parallel. If that's still slow, pre-aggregate data in a separate DO that updates asynchronously.
Inconsistent results. If your cross-room query returns different numbers than the old D1, check for eventual consistency. If you need strong consistency, use a single DO for that specific query, or use D1 as a read replica.
Data loss during migration. Always export a backup of each room's data before moving. If a DO import fails, you can restore from backup.
Frequently Asked Questions
Can I still use D1 after moving to Durable Objects?
Yes, you can keep D1 for global data or as a read replica. The goal is to move per-room data to DOs for strong consistency and low latency.
How do I handle cross-room transactions?
D1 transactions span rooms, but DOs don't. Redesign the transaction as a saga: perform steps in each DO, with compensating actions if a step fails.
What if a cross-room query is used by an admin dashboard?
For admin dashboards, you can maintain a separate D1 table that is updated asynchronously from each DO. This avoids fan-out on every request.
How do I know if a query is cross-room?
Look for queries that don't have a room_id in the WHERE clause, or that join tables from different rooms. Also check for subqueries that span rooms.
Is it safe to migrate all at once?
No, migrate room by room. This reduces risk and allows you to rollback if issues arise.
What happens to my D1 database after migration?
You can delete the per-room tables from D1, but keep a backup. You may also keep D1 for other purposes.