SQL Database
Powerful SQL databases that scale with your agents. Cloudflare D1 provides serverless SQLite databases with automatic scaling, global read replicas, and built-in agent storage capabilities. Perfect for storing structured data, user information, and complex relationships that agents need to track.
Key Features
- Global Read Replicas: Automatically replicated across multiple regions for faster reads
- Serverless Scaling: Scales to zero when not in use, handles thousands of queries per second
- ACID Compliance: Full transaction support with guaranteed data consistency
- Agent Storage: Built-in SQLite storage within Durable Objects for local agent data
- Sessions API: Sequential consistency across distributed replicas
Wrangler Configuration
First, add D1 databases in your wrangler.json:
Generate your database id by using wrangler d1 create database-name-here and paste the responding db.
NOTE: In the future, the platform will automate this for you
TypeScript API Reference
You can access D1 databases via the env of the Agent or MCP Tool:
Global D1 Database Methods
prepare(query: string): D1PreparedStatement
Creates a prepared statement for SQL queries. Supports parameter binding for security and performance.
withSession(bookmark?: string): D1DatabaseSession
Creates a new session for sequential consistency across read replicas. Essential for maintaining data consistency. Optional if consistency isn't required.
batch(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>
Executes multiple prepared statements in a single transaction for better performance.
exec(query: string): Promise<D1ExecResult>
Executes raw SQL statements. Mainly used for schema changes and bulk operations.
Agent and MCP Tool Local Storage Methods
ctx.storage.sql.exec(query: string): Promise<SqlStorageResult>
Executes SQL directly on the agent's local SQLite database within the Durable Object.
ctx.storage.sql.prepare(query: string): SqlStorageStatement
Creates prepared statements for the local SQLite database with parameter binding.
Database Types: Global vs Agent/MCP Tool Storage
Global D1 Service
Pros:
- Global read replicas for faster access worldwide (30-75ms typical replication lag)
- Automatic backups with Time Travel (30-day point-in-time recovery)
- Multi-region consistency with Sessions API
- Shared data across multiple agents and services
- Familiar SQL migration tools
Cons:
- Network latency for write operations (writes always go to primary region)
- More complex setup for simple agent-local data
- Additional D1 usage costs based on rows read/written
Agent Local Storage
Pros:
- Zero network latency for agent and mcp tool data (sub-millisecond access)
- No additional D1 usage costs (included in Durable Object pricing)
- Immediate consistency (no replication lag)
- Programmatic backup capabilities via Durable Object snapshots
- Perfect for agent-specific state and temporary data
Cons:
- No global read replicas (data isolated to single region)
- Storage processing limited by Durable Object constraints (128MB memory limit)
- Data isolated to individual agent instances
- Backup/restore requires custom implementation
- Setup SQL migrations manually in code
Examples
User Profile Management Agent
Analytics Data Processing Agent
Local Chat Session Agent
MCP Tool Integration
Best Practices
Query Optimization
Transaction Management
Storage Strategy
Backup & Recovery
Global D1 Backup
D1 databases automatically include Time Travel - point-in-time recovery for the last 30 days:
Restoration Process:
- D1 replays the Write-Ahead Log up to your specified point in time
- Creates a new database instance with the restored state
- Updates your binding to point to the restored database
- Previous database remains available for verification
Agent Storage Backup
For agent local storage, backups are handled programmatically using Durable Object's Point-in-Time Recovery (PITR) API:
Point-in-Time Recovery Features:
getCurrentBookmark(): Gets current state bookmark for backup referencegetBookmarkForTime(timestamp): Gets bookmark for specific timestamp (last 30 days)onNextSessionRestoreBookmark(bookmark): Restores Durable Object to specific bookmark- Automatic backups: Using Durable Object alarms for scheduled backups
- Backup metadata: Stored externally while leveraging built-in PITR for actual data
Limitations & Considerations
Global D1 Service
- Database Size: 10GB maximum per database
- Query Timeout: 30 seconds maximum execution time
- Concurrent Connections: 100 concurrent connections per database
- Replica Lag: 30-75ms typical replication lag between regions
- Cold Start: ~100ms latency on first query after idle period
Agent Local Storage
- Storage Size: 128MB practical limit per Durable Object
- No Global Replicas: Data isolated to single Durable Object instance
- Manual Backups: Requires custom backup implementation
- Limited Concurrency: Single-threaded SQLite within Durable Object
Related Services
- Memory Store (KV) - Fast access to frequently used data
- Cache - Cache expensive query results
- Analytics Storage - Time-series data for metrics
- Workflows - Orchestrate database operations across agents