Course contentsShow
← System Design
Lesson 262 of 1,9197. Database Scaling: ShardingFree lesson

Referential Integrity Across Shards

Understand the loss of foreign key guarantees when related data lives on different shards.

Referential Integrity Across Shards

You'll learn: Why foreign key relationships break when data splits across different database shards.

The Problem with Split Relationships

In a traditional single-database system, foreign keys enforce referential integrity—the database automatically ensures that if Order #123 references Customer #456, Customer #456 must exist. The database won't let you delete a customer who has orders, or create an order for a non-existent customer.

When you shard your database, this safety net disappears.

Why Sharding Breaks Foreign Keys

Imagine you shard by customer_id: Customer #456 lives on Shard A, but their orders (sharded by order_id) might live on Shard B or Shard C. Your database can no longer enforce foreign key constraints across these shards because each shard is an independent database that can't "see" data on other shards.

Real-world analogy: It's like having library branches that each manage their own inventory. Branch A can't verify whether a book referenced in Branch B's checkout system actually exists—they're separate systems without direct knowledge of each other.

Consequences You Must Handle

  • Orphaned records: An order might reference a deleted customer
  • Dangling references: Creating records pointing to non-existent entities
  • No cascade operations: Deleting a customer won't automatically delete their orders on another shard

You must handle referential integrity at the application level: validate references before writes, implement cleanup jobs for orphaned data, and carefully design transactions when related entities span shards.

Key Takeaway: Sharding eliminates database-enforced foreign key constraints across shards, forcing your application code to maintain referential integrity manually.