Database Sharding in System Designing
advance · System Designing
While Database Replication scales your read throughput by adding mirror copies of the data, it does not solve the problem of scaling write throughput. On a single primary node, you will eventually hit limits on disk storage capacity and CPU performance. To scale writes, you must use Database Sharding . Sharding is the architectural pattern of breaking up a single massive database table and distributing the pieces horizontally across multiple completely independent database instances (called shards ). 1. Shared-Nothing Architecture Unlike replication, where every node holds a copy of the entire dataset, sharding uses a Shared-Nothing Architecture . Each shard is a distinct database engine that owns a mutually exclusive subset of the total data. 2. Shard Key Choice Is Critical A Shard Key is the specific column or attribute in your data schema that determines exactly which shard a particular row will be routed to. Once you choose a shard key, it is incredibly difficult to change without taking your entire application offline for a massive data migration. Common Sharding Strategies: Range-Based Sharding: Data is split based on a range of values (e.g., Shard 1 holds users with names A–G, Shard 2 holds H–O, etc.). The Flaw: It naturally creates uneven distributions. If you suddenly get a million new users whose names start with 'J', Shard 2 will experience a massive performance bottleneck while Shard 1 sits completely idle. Hash-Based Sharding: The system takes the shard key (like user_id ), passes it through a mathematical hash function, and uses the modulus operator against the total number of shards ( $N$ ) to find the destination: $\text{Shard ID} = \text{Hash}(\text{user\_id}) \pmod N$ The Flaw: If your system grows and you need to add an extra shard (changing $N$ to $N+1$ ), the mathematical output for almost every single key changes. This forces you to re-shard and move up to 90% of your existing data across the network. 3. The Hotspot Problem (Uneven Distribution) A Hotspot occurs when a specific shard receives a disproportionate amount of read or write traffic compared to the rest of the cluster, causing it to run out of disk space or max out its CPU. This is almost always caused by a poor choice of a shard key: The Celebrity Problem: If you shard a social media application by actor_id or user_id , a standard user's shard will handle minimal traffic. However, the shard holding a celebrity with 100 million followers will buckle under the load of millions of concurrent writes and reads, creating a critical hotspot. 4. Resolving Re-sharding: Consistent Hashing To scale a sharded database horizontally without triggering a massive data migration nightmare every time you add a new machine, systems use Consistent Hashing . How it works: Imagine a conceptual circle mapped with numeric positions from $0$ to
^{32}-1$ (The Hash Ring ). Both your database servers (shards) and your data keys are passed through a hash function that maps them to a specific point along this ring. To determine where a data row lives, you locate its key on the ring and walk clockwise until you hit the first available database server. The Elegant Benefit: When you add a new shard node to a consistent hashing ring, you do not need to reassign all your data . The new shard only intercepts a small fraction of the keys from its immediate counter-clockwise neighbor. On average, only $\frac{K}{N}$ keys need to be moved (where $K$ is the total number of keys and $N$ is the total number of shards). 5. The Massively Complex Trade-offs of Sharding Before implementing sharding, you must be prepared to handle severe application-layer complexity: No Multi-Shard Joins: You cannot easily execute a SQL JOIN query across tables that sit on different physical shards over a network. Your application code must execute multiple independent queries and stitch the data together manually in memory. Loss of Referential Integrity: Enforcing global foreign key constraints across different machines is near impossible without introducing massive network performance penalties. Complex Transactions: Standard ACID properties break down across shards. Ensuring that a transaction fully succeeds or fails across two separate databases requires slow, complex coordination algorithms like the Two-Phase Commit (2PC) protocol.
Careeroza — One-stop Zone for Aspirants
Study material, Careeroza mentorship, tech jobs, and career guidance on careeroza.com.
Public study materials
- Node.js — Server-side JavaScript (nodejs)
- Getting started · basic
- JavaScript on the server · basic
- CommonJS modules · basic
- ES modules (ESM) · basic
- npm & package management · basic
- Asynchronous JavaScript in Node · basic
- The event loop · basic
- Essential core utilities · basic
- process & configuration · basic
- File system basics · basic
- HTTP & HTTPS servers · medium
- Streams · medium
- Events & EventEmitter · medium
- Advanced filesystem · medium
- crypto · medium
- Compression & encoding · medium
- Child processes · medium
- net, dgram & DNS · medium
- readline, timers & scheduling · medium
- Testing & diagnostics (intro) · medium
- Worker threads · advance
- cluster & multi-process scaling · advance
- Performance & tuning · advance
- Debugging & observability · advance
- Security hardening · advance
- Native addons & N-API · advance
- Architecture patterns · advance
- Graceful shutdown · advance
- 100 Questions · interview questions
- Django (Django)
- What is Django · basic
- Installing Django · basic
- Features of Django · basic
- MVT Architecture · basic
- Django vs Flask · basic
- Creating Project & Creating App · basic
- Django Project Structure · basic
- URL Routing · basic
- Views · basic
- Templates · basic
- Static & Media Files · medium
- Models · medium
- ORM (Object Relational Mapping) · medium
- Model Relationships · medium
- Migrations · medium
- Django Admin · medium
- Forms · medium
- Authentication · medium
- Authorization · medium
- Middleware · medium
- Signals · medium
- Class Based Views Deep Dive · advance
- Generic Views · advance
- File Handling · advance
- Django REST Framework (DRF) · advance
- Advanced ORM · advance
- Caching · advance
- Asynchronous Django · advance
- Background Tasks · advance
- Interview Questions · interview-questions
- Python (Python)
- Python Fundamentals · basic
- Control Flow · basic
- Strings · basic
- Collections / Data Structures · basic
- Functions · basic
- Modules and Packages · basic
- File Handling · basic
- Exception Handling · basic
- Object-Oriented Programming (OOP · medium
- Advanced Python Concepts · advance
- Functional Programming · advance
- Multithreading & Multiprocessing · advance
- Async Programming · advance
- JavaScript (JavaScript)
- JS Introduction · basic
- Variables & Data Types · basic
- Operators · basic
- Control Flow · basic
- Functions · basic
- Scope & Execution · basic
- Closures · basic
- Objects · basic
- Arrays · basic
- Strings · basic
- DOM Manipulation · basic
- Browser APIs · medium
- Asynchronous JavaScript · medium
- Fetch & APIs · medium
- ES6+ Features · medium
- OOP in JavaScript · medium
- Prototype & Inheritance · advance
- Advanced Functions · advance
- Memory Management · advance
- Error Handling · advance
- Modules · advance
- Advanced Async Concepts · advance
- Functional Programming · advance
- JavaScript Internals · advance
- Performance Optimization · advance
- System Designing (System Designing)
- Day-1 : What is system Designing ? · basic
- Day-2 : Vertical vs. Horizontal Scaling · basic
- Day-3:How to do vertical scaling ? · basic
- Day4:How to do horizaontal scaling ? · basic
- Day:5TCP vs UDP · basic
- Day6:IP & DNS · basic
- Day7:Client-Server Model · basic
- Day8:HTTP & HTTPS · basic
- Databases (SQL vs NoSQL) · medium
- Caching · medium
- Day9:Latency & Throughput · basic
- Load Balancing · medium
- Indexes & Query Optimization · medium
- CDN · medium
- Proxies · medium
- Message Queues · medium
- Horizontal vs Vertical Scaling · medium
- Database Replication · advance
- Database Sharding · advance
- Consistent Hashing · advance
- CAP Theorem · advance
- Rate Limiting · advance
- Service Discovery · advance
- Event-Driven Architecture · advance
- API Gateway · advance
- Distributed Consensus · expert
- Microservices · expert
- Observability · expert
- Idempotency · expert
- PACELC Theorem · expert
- Two-Phase Commit · expert
- Back-of-Envelope Estimation · expert
- Designing for Failure · expert
- Angular (Angular)
- Angular Fundamentals · basic
- Project Structure · basic
- Components & Templates · basic
- Data Binding · basic
- Directives · basic
- Pipes · basic
- Component Communication · basic
- Lifecycle Hooks · basic
- Routing Basics · basic
- Routing · basic
- API Calls · basic
- Forms · medium
- Routing · medium
- Services & Dependency Injection · medium
- RxJS & Observables · medium
- Authentication & Security · medium
- Component Interaction · medium
- State Management Basics · medium
- Error Handiling · medium
- Perfomance Basic · medium
- Real World Features · medium
- Advanced Angular Architecture · advance
- Change Detection · advance
- Advanced RxJS · advance
- State Management · advance
- Dynamic Rendering · advance
- Perfomance Optimization · advance
- Modern Angular · advance
- Express.js — Web APIs & middleware (expressjs)
- Application setup · basic
- Routing deep dive · basic
- 1. MVC / Layered Architecture · medium
- Validation · medium
- File uploads · medium
- Sessions & auth (stateful) · medium
- Passport & strategies · medium
- Templating & SSR · medium
- WebSockets & SSE · medium
- Security middleware · advance
- Reverse proxies & trust · advance
- Performance · advance
- API design & versioning · advance
- Testing with Supertest · advance
- GraphQL & tRPC (overview) · advance
- Deployment checklist · advance
- Middlewares · basic
- Request & Response · basic
- SQL (SQL)
- SQL Fundamentals · basic
- Database Operations · basic
- Table Operations · basic
- CRUD Operations · basic
- Filtering & Operators · basic
- SQL Functions · basic
- GROUPING Data · basic
- Joins · medium
- Constraints · basic
- Subqueries · medium
- Set Operators · medium
- Views · medium
- Indexes · medium
- Normalization · advance
- Transactions · advance
- Stored Procedures & Functions · advance
- Triggers · advance
- Advanced SQL · advance
- Query Optimization · advance
- Database Design · advance
- SQL Security · advance
- Backup & Recovery · advance
- Questions · interview questions
- STAR (Situation, Task, Action, and Result) (Situation Based Questions)
- System Architecture (System Architecture)
- Fundamentals of System Architecture · basic
- Distributed System Basics · basic
- System Reliability Concepts · basic
- Scaling Concepts · basic
- Networking Basics · basic
- Web Communication · basic
- API Communication · basic
- Proxy & Delivery Systems · basic
- Web Architecture Basics · basic
- Rendering Architectures · basic
- Frontend Advanced Concepts · basic
- Message Queue Basics · medium
- What is Load Balancer · medium
- Load Balancing Algorithms · medium
- API Design Basics · medium
- API Protection · medium
- Authentication Basics · medium
- Security Tokens · medium
- Security Threats · medium
- Encryption & Security · medium
- SQL Database Basics · medium
- SQL Scaling Concepts · medium
- NoSQL Databases · medium
- Database Optimization · medium
- Replication Strategies · medium
- Caching Basics · medium
- Cache Storage Systems · medium
- Cache Strategies · medium
- Event-Driven Systems · advance
- Queue Reliability · advance
- Microservices Basics · advance
- Microservice Communication · advance
- Distributed Transactions · advance
- DevOps Basics · advance
- Automation Tools · advance
- Deployment Strategies · advance
- Monitoring Basics · advance
- Monitoring Tools · advance
- Distributed System Concepts · advance
- Distributed Algorithms · advance
- MongoDB — Documents & data modeling (MongoDB)
- Introduction · basic
- Shell, Compass & tools · basic
- Databases & collections · basic
- CRUD operations · basic
- Indexes deep dive · medium
- Explain plans & performance · medium
- Aggregation framework · medium
- Schema design patterns · medium
- Mongoose basics · medium
- Mongoose advanced · medium
- Drivers & connection · medium
- Operators for updates & arrays · medium
- Replication & read preferences · advance
- Write concern & read concern · advance
- Multi-document transactions · advance
- Change streams · advance
- Sharding (overview) · advance
- Atlas Search & full-text · advance
- GridFS & large files · advance
- Backup, restore & ops · advance
- AWS Crash Course (AWS)
- What is Cloud ? · basic
- What is AWS ? · basic
- If not cloud ? · basic
- Cloud Computing · basic
- AWS Pricing · basic
- AWS Shared Responsibility Model · basic
- AWS Management Console · basic
- AWS SDKs · basic
- AWS IAM · medium
- Users, Groups, Roles · medium
- Policies · medium
- AWS Organizations · medium
- AWS Cognito · medium
- AWS Directory Service · medium
- AWS KMS (Key Management Service) · medium
- AWS Secrets Manager · medium
- AWS Shield · medium
- AWS WAF · medium
- AWS Inspector · medium
- AWS GuardDuty · medium
- EC2 · advance
- Launching EC2 Instances · advance
- EBS Volumes · advance
- Security Groups · advance
- Key Pairs · advance
- Elastic IP · advance
- User Data Scripts · advance
- Auto Scaling · advance
- Load Balancers · advance
- ALB · advance
- NLB · advance
- Serverless Compute ,AWS Lambda, Lambda Layers · advance
- Event-Driven Architecture · advance
- ECS · advance
- EKS · advance