Launched in 2006, Twitter took the next four years to become a cautionary tale of how a site can fail to scale. So unreliable was the service that its error page showed a cartoon of a whale being carried by a flock of birds and read "Twitter is over capacity" and this became a cultural phenomenon.
So frequent did the "fail whale" appear that users began to treat it as a joke. What lay behind the joke was a real problem. Twitter's monolithic Ruby on Rails design was not built for the load it got and adding capacity needed re-architecting systems under pressure from live production.
By around 2012, after years of work that broke down its monolithic architecture into independent services, added caching layers and redesigned how databases were accessed, Twitter put an end to the fail whale era.
Engineering blog posts that documented these transformations through services such as the Firehose, Timeline and Tweet store became required reading for a whole generation of engineers who were learning to build systems at scale.
Scaling is not about getting bigger machines. Systems that grow gracefully as demand goes up are what it is about. They add capacity without needing to rebuild from scratch and they solve the right problem instead of putting more hardware into the wrong architecture.
Of all scaling problems, the most costly is the one you solve with hardware rather than architecture. When servers get added to a poorly designed system, what results is a poorly designed system with more servers. Architectural rework is unavoidable and the only question is whether you do it proactively or under pressure of crisis.
The Fundamental Scaling Approaches
Two philosophies govern how systems grow to handle more load.[2] Every scaling decision traces back to one or both.
Vertical Scaling (Scaling Up)
Vertical scaling adds more resources to a single machine: more CPU cores, more RAM, faster storage, faster network interfaces. It is the path of least resistance because it requires no architectural changes. The same application that ran on a 4-core machine runs on a 96-core machine: just faster.
Upgrading the server gives instant gain of capacity and that appeal is obvious. Within limits it works and the limits are hard.
- Physical machines have maximum configurations
- Maximum sizes exist for cloud instance types and AWS's x2iedn.32xlarge comes with 128 vCPUs, 4TB RAM and costs about $26.70 per hour on demand.
- At the top end, the link between cost and performance stops being linear and doubling resources does not most often double performance.
- A single powerful machine is still a single point of failure
For workloads that truly cannot be split up (some databases and stateful services), vertical scaling has value both as a quick fix and as the right way to go. Relying on it as a long-term strategy means hitting a ceiling eventually.
Horizontal Scaling (Scaling Out)
Horizontal scaling brings in more machines and spreads the load among them. One powerful server no longer deals with all requests. Twenty smaller servers each take 5% of the traffic. Capacity can be added by adding servers and that can go on indefinitely.
The requirement is architectural: applications must be designed for distribution.
- Request state cannot live on a single server (because the load balancer may route any request to any server)
- Database writes must handle concurrent access from many application servers
- Communication between components must work across network boundaries
- Session data must be externalized to shared storage
This architectural requirement is real work. But it is the essential trade-off that enables true scalability. Netflix serves hundreds of millions of users from their cloud infrastructure because every component in their architecture can scale horizontally.
Fleets of instances that expand and contract with demand run their streaming video servers, recommendation engine, account management services and supporting systems.
| Factor | Vertical | Horizontal |
|---|---|---|
| Architecture changes needed | No | Yes (stateless design required) |
| Practical upper limit | Hardware maximum | Virtually unlimited |
| Single point of failure | Yes | No (if designed correctly) |
| Cost at scale | Expensive per unit | Linear |
| Downtime to scale | Usually requires restart | None (add instances live) |
| Best for | Databases, stateful services | Web servers, API services |
Building Blocks of a Scalable Architecture
Scalable systems are not monolithic, they are compositions of components, each handling a specific responsibility and each capable of scaling independently.
Load Balancers: The Traffic Director
A load balancer sits in front of multiple application servers and distributes incoming requests across them. Without a load balancer, additional servers do not help because all traffic still arrives at one server.
Modern cloud load balancers do more than simple round-robin distribution:
Health checking. Every backend server is checked continuously and any that are unhealthy get taken out of rotation. Once the server recovers, the load balancer puts it back into service automatically. That gives automatic failover without needing any manual work.
Session affinity (sticky sessions). It routes requests from the same user to the same server so as to keep session state intact. Often this is a crutch that stops proper statelessness from being designed and the solution is to use it only temporarily until state is removed from application servers.
SSL/TLS termination. This takes care of SSL encryption and decryption at the load balancer level that reduces the computational load on application servers.
Path-based routing. Route /api/* requests to the API server fleet and /static/* requests to the CDN origin. Depending on how the servers are configured, requests of different types go to different server groups.
AWS Application Load Balancer (ALB). This handles Layer 7 (HTTP/HTTPS) load balancing along with path and header routing as well as WebSocket support and direct integration with AWS services.
AWS Network Load Balancer (NLB). This handles layer 4 (TCP/UDP) load balancing for maximum throughput and minimum latency and it is used for non-HTTP workloads.
Global load balancing. Traffic goes to the geographically closest healthy infrastructure and global users experience less latency as services such as AWS Global Accelerator and Cloudflare route traffic that way.
Example: Airbnb serves traffic to millions of users simultaneously through a multi-tier load balancing architecture. AWS ALBs distribute requests to multiple application server fleets, with separate fleets for the website, mobile API, and internal services.
Each fleet auto-scales independently based on its specific traffic patterns.
Stateless Application Servers
For horizontal scaling to work, application servers must be stateless. This means they cannot store anything in local memory that is needed across requests.
What must be externalized:
- User sessions: Move to Redis, Memcached, or a database
- Uploaded files: Move to object storage (S3, GCS)
- Application cache: Move to shared cache layer (Redis, Memcached)
- Locks and semaphores: Move to distributed locking (Redis SETNX, Zookeeper)
When application servers are stateless, the load balancer can route requests to any available server without concern for which server the user previously used. Scaling up means adding instances to the pool.
To scale down or recover from server failure requires taking instances out of the pool. Automatic adjustment takes place across the system.
Caching: The Highest-Leverage Optimization
Caching holds onto the results of expensive operations such as database queries, API calls and computations so that future requests for the same data can come out of fast memory instead of going through the expensive operation again.
The performance gain is huge. A database query that takes 100ms can come out of Redis in 0.1ms instead and that is a 1,000 times gain. And when 80% of traffic asks for the same 20% of data (a common pattern), caching that 20% gets rid of 80% of the database load.
Application-level caching (Redis, Memcached): The application checks the cache before querying the database.[6] If the value is in cache, return it immediately. If not, query the database, store the result in cache with an expiration, and return it.
CDN caching (CloudFront, Fastly, Cloudflare): Edge servers distributed globally cache static assets (images, JavaScript, CSS) close to users. Instead of all 200x100px thumbnail images being fetched from your origin server, they are cached at 300+ edge locations worldwide.
A user in Tokyo gets the image from a Tokyo edge server rather than from your US-based origin.
Database query caching: Databases (MySQL, PostgreSQL) cache query execution plans and sometimes results. Proper indexing makes the database's internal cache far more effective.
Full-page or fragment caching: Cache entire rendered HTML pages (for high-traffic, rarely-changing pages) or individual page fragments (a product listing, a navigation menu) to reduce server rendering load.
Making sure that cached data stays fresh when the underlying data changes is the hard part as cache invalidation goes. Strategies.
- TTL-based expiration. The cache expires after N seconds whatever changes there are. It is simple but it serves up to TTL seconds of stale data.
- Event-based invalidation. Cache entries get removed explicitly when the data underneath changes. It is more complex but makes sure the cache stays fresh.
- Write-through caching. On writes, update the cache and the database at once. The cache is always consistent but it brings in write latency.
- Cache-aside (lazy loading): Applications manage the cache explicitly: check cache, miss, load from database, populate cache. Most common pattern.
Example: Pinterest serves hundreds of billions of pin impressions per month.[9] Their Redis caching layer handles the majority of read traffic, with the underlying MySQL databases handling only cache misses and writes.
This architecture allows them to serve massive read traffic without proportionally massive database infrastructure.
Message Queues: Decoupling Producers and Consumers
Message queues (AWS SQS, RabbitMQ, Apache Kafka) decouple components that produce work from components that perform it. Instead of processing a task synchronously (user waits while the server does the work), the application puts the task on a queue and immediately responds to the user.
Worker processes consume tasks from the queue at their own pace.
The scaling benefits:
Absorbs traffic spikes. When 10,000 image processing jobs arrive in a minute and your worker fleet manages 1,000 per minute, the queue builds up 9,000 jobs. Over 10 minutes workers get through them. The system would have to manage 10,000 simultaneous jobs without the queue or it would run into capacity errors.
Independent scaling. Web servers and workers scale independently according to the load on each of them. Web servers scale based on the volume of HTTP requests and workers scale based on queue depth.
Resilience. When jobs fail, they can be retried automatically. At the same time, dead letter queues take in jobs that fail over and over for investigation without blocking the main processing pipeline.
Async processing: Operations like sending email, generating reports, resizing images, and processing payments do not require the user to wait. Queue them; respond to the user immediately.
Example: Stripe processes billions of payment events through a distributed queue system. When a payment is submitted, the initial API response is fast (the payment is queued).
Asynchronously, worker processes manage the complex validation, fraud detection, bank communication and notification workflows. The result is that Stripe's API can stay fast no matter how complex what follows downstream.
Database Scaling: The Hard Part
Databases are the hardest component to scale because they are stateful, consistency-sensitive, and central to application logic. Database scaling should be approached in order of increasing complexity.
Start With Indexing
Make sure the database has proper indexes before doing any other optimization. An unindexed query on a table of 10 million rows may scan every row and that takes seconds. With a proper index in place, the same query returns in milliseconds.
Signs you need indexes: Slow queries identified with EXPLAIN or EXPLAIN ANALYZE (both PostgreSQL and MySQL 8.0.18+), queries that show "full table scan" in execution plans, queries filtering on columns that are not in any index.
Index trade-offs. Indexes help reads go faster but they make writes slower since every write has to update the index and take up storage. Put indexes on columns that appear in WHERE clauses of frequently run slow queries. Do not put indexes on every column without thought.
Tools that analyze database queries (pg_stat_statements for PostgreSQL and slow query log for MySQL) find the queries that consume the most total time and these are the highest-leverage optimization targets.
Read Replicas
Reads far outstrip writes by 10 to 1 or more in most web applications. Read replicas take the primary database and copy it asynchronously and they handle read queries too. That spreads the read load across many instances.
Writes (INSERT, UPDATE, DELETE) go to the primary and reads go to a replica (or to a load balancer spreading across several replicas). A replica adds read capacity by multiplying it and the primary deals only with writes and with the overhead of replicating data.
Replication lag. Depending on how much data gets written, replicas can lag behind the primary by milliseconds to seconds. Any application that needs to read data right after writing it (such as displaying a user what they just did) has to pull from the primary for that particular operation.
Managed read replicas with automatic failover promotion are supported by AWS RDS, Google Cloud SQL and Azure Database all.
Connection Pooling
Every database connection uses resources from the database server (memory and file descriptors). When a web app has 100 application server instances each opening 10 connections, it needs 1,000 database connections at once. Practical limits in the hundreds apply to PostgreSQL. MySQL can handle more but it has limits as well.
PgBouncer (PostgreSQL) and ProxySQL (MySQL) pool connections: many application connections share a smaller pool of actual database connections. Applications open connections to the pooler; the pooler multiplexes them across a small set of actual connections.
Once set up, connection pooling makes less work for database servers and prevents connections from running out during traffic spikes and it comes almost free (it adds little latency).
Vertical Scaling for Databases
Unlike application servers, databases often benefit from vertical scaling before horizontal scaling because:
- More of the working dataset fits in memory as RAM size grows and that cuts disk I/O by a large amount.
- More CPU improves query execution, particularly for complex analytical queries
- Faster storage (NVMe SSDs vs. SATA SSDs) dramatically reduces I/O bottlenecks
Live vertical scaling is supported by Amazon RDS, Google Cloud SQL and Azure Database with little downtime for many database types.
Sharding
Database sharding partitions data across multiple independent database instances. Each shard holds a subset of the data (e.g., users with IDs 0-999999 on shard 1, users 1000000-1999999 on shard 2). Read and write load distributes across shards proportionally.
Sharding dramatically increases both read and write capacity. Instagram sharded their PostgreSQL databases to handle hundreds of millions of users.
The cost is significant complexity:
- To get cross-shard queries working (for instance, "find all users who bought product X") needs a query of all shards followed by aggregation of the results.
- Resharding (adding more shards as data grows) is operationally challenging
- Application logic must determine which shard a given record lives on
- Transactions spanning multiple shards require distributed transaction protocols
Only shard when simpler approaches fail. Numerous high-traffic apps get through their entire life without sharding by using aggressive caching, read replicas and good indexing.[10]
NewSQL and Distributed Databases
A class of databases provides the SQL interface and ACID guarantees of traditional relational databases while supporting horizontal scaling:
Google Spanner. This is Google's globally distributed relational database. It is used internally for Google Ads and other critical systems. Cloud Spanner is available on Google Cloud as well. The service gives strong consistency across global distributions.
CockroachDB. An open-source distributed SQL database that draws inspiration from Spanner. It has automatic sharding, horizontal scaling and strong consistency built in.
Amazon Aurora, which is a cloud-native relational database from AWS that works with MySQL and PostgreSQL and has distributed storage that scales automatically as well as up to 15 read replicas.
These databases make scaling easier by managing distribution behind the scenes but they come at a cost of higher per-record pricing than for self-managed databases.
Auto-Scaling: Dynamic Capacity Management
Auto-scaling. Following what it observes, the number of running instances adjusts automatically and capacity stays matched to actual demand continuously instead of being over-provisioned for peak load.[5]
How Auto-Scaling Works
Auto-scaling groups cover auto-scaling rules for AWS EC2 Auto Scaling, Google Managed Instance Groups as well as Azure Virtual Machine Scale Sets.
- Minimum capacity: Never fewer than N instances (ensures baseline availability)
- Maximum capacity: Never more than M instances (prevents runaway costs)
- Scaling policies: When to add or remove instances
Common scaling triggers:
- Target tracking: "Maintain average CPU utilization at 60%." When above 60%, add instances. When below 60%, remove them.
- Step scaling: Add 2 instances when CPU exceeds 70%, add 5 when it exceeds 85%
- Scheduled scaling. Put in more instances ahead of a known traffic spike such as Monday morning, a scheduled marketing email or a sporting event.
- Queue-based scaling. Add worker instances when the queue grows and remove them when it shrinks as a way to scale based on queue depth.
Scaling Timing
Scale-up should happen proactively, before performance degrades. Scaling reactions that take 5 minutes to complete cannot protect against traffic spikes that saturate capacity in 2 minutes.
Solutions:
- Predictive scaling: AWS Predictive Scaling uses machine learning to predict traffic patterns and pre-scales before predicted peaks
- Scale-up aggressively, scale-down conservatively: Use fast scale-up thresholds (add instances at 60% CPU) and slow scale-down thresholds (remove instances only at 20% CPU for 15 minutes)
- Warm-up periods: New instances often need time to initialize (JVM warmup, connection pool establishment, cache warming). Configure auto-scaling to account for warmup time before routing full traffic to new instances
Example. At meal times, DoorDash sees traffic spikes that are large, predictable each day and repeat daily.
Scheduled scaling in their auto-scaling config pre-provisions capacity before lunch and dinner rushes instead of waiting for load spikes that triggers reactive scaling. That gets rid of the latency between traffic going up and capacity being added.
CDN: Global Performance at Scale
A Content Delivery Network (CDN) caches content at edge locations distributed globally, serving users from a location close to them rather than from a single origin server.
Latency alone from the round-trip network time adds up to an enormous performance hit. An Australian user getting an image from a US server runs into 150 to 300 ms of delay. The same image stored at a Sydney CDN edge server gives a latency of 2 to 10 ms.
Global users get most of the latency out of static assets like images, JavaScript bundles, CSS and fonts thanks to CDN caching.
CDNs go beyond latency by reducing the load on origin servers as well. With a popular image getting 1 million requests a day and the CDN cache hitting 95% of them, only 50,000 requests reach the origin server. Origin traffic and cost both drop by 20 times.
AWS CloudFront, Fastly, Cloudflare, and Akamai are the major CDN providers. Configuration:
- Define cache behaviors: which paths cache for how long
- Cache TTLs should be set properly. Static assets such as images and fonts can cache for years using versioned filenames and HTML pages most often cache for seconds to minutes.
- Enable compression (gzip/Brotli) to reduce transfer size
- Configure georestrictions if content licensing requires it
Modern CDNs also support edge computing: running code at edge locations to handle personalization, authentication, and other logic close to users. Cloudflare Workers, AWS Lambda@Edge, and Fastly Compute@Edge execute lightweight functions at CDN nodes worldwide.
Architecture Patterns for Scale
Architectural patterns beyond the individual components allow systems to scale to higher levels than monolithic designs can manage.
The Microservices Tradeoff
Decomposing a monolithic application into independently deployable services allows each service to scale based on its specific demand. The user authentication service may need 10 instances while the video encoding service needs 50. Each service can use the technology stack optimized for its workload.[3]
The cost. Operational complexity goes up markedly. With more services come more deployments, more monitoring and more overhead from inter-service communication as well as more ways a service can fail (a service may fail because a dependency is slow).
Microservices are appropriate for:
- Large engineering organizations where independent deployment reduces coordination overhead
- Services with dramatically different scaling requirements
- Systems where team autonomy and technology choice diversity provide real value
They are inappropriate for:
- Small teams (the operational overhead exceeds the benefit)
- Systems with limited scaling requirements
- Applications early in development where boundaries are unclear
Example. Amazon's change from a monolith to microservices is among the examples most cited in the industry. From about 2001 onward, the company broke down its retail site into hundreds of independent services. The move took years and brought large amounts of pain.
The result: Amazon can now deploy code thousands of times per day with each service team working independently, and each service can scale based on its specific demand rather than the entire site scaling together.
Event-Driven Architecture
Components communicate through events (messages) rather than direct synchronous API calls.[4] When an order is placed, an "order created" event is published to a message bus.
The inventory service, the notification service, the analytics service, and the fulfillment service each subscribe to and independently process the event.
Scaling benefits:
- Each consumer scales independently based on its processing requirements
- Traffic spikes are buffered by the event log
- Components are loosely coupled: the order service does not know or care which services consume its events
- New consumers can be added without modifying producers
High-throughput systems use Apache Kafka as the dominant event streaming platform.[7] Managed options are available through AWS SNS/SQS, Google Pub/Sub and Azure Event Hub.
CQRS and Read-Optimized Stores
CQRS (Command Query Responsibility Segregation) keeps write operations (commands) separate from read operations (queries). It does that by using different data stores that have been optimized for each.
Writes go to a normalized relational database optimized for consistency. Reads are served from a denormalized, search-optimized store (Elasticsearch, Redis, a read-optimized PostgreSQL schema) updated asynchronously from the write store.
Solving a common problem where read queries across normalized tables call for expensive joins, this pattern addresses complex read queries. Reads can draw from pre-computed data held in a denormalized read store and with optimal indexing.
Example. LinkedIn's "People You May Know" feature keeps a denormalized graph store optimized for fast graph traversal. It is updated asynchronously from the transactional system.
Instead of running on the transactional database, complex graph algorithms work on the read-optimized store. That gives recommendations scalability that is separate from how core user data operations scale.
Performance Measurement: Finding the Real Bottleneck
Scaling the wrong component wastes money without improving performance. Measurement identifies the actual bottleneck.
Application performance monitoring (APM) Tracing requests through distributed systems with tools such as Datadog APM, New Relic and Honeycomb shows where time goes. It shows which database queries are slow, which service calls take long and where errors occur.
Load testing. Realistic traffic patterns get simulated by tools such as k6, Gatling and Apache JMeter so that breaking points can be found before real traffic discovers them. A load test that hits only cached data will not show up database bottlenecks and use realistic data volumes and access patterns for load testing.
Database query analysis: PostgreSQL's pg_stat_statements extension tracks query execution frequency and cumulative time. Queries that run 100,000 times per day at 5ms each cost 500 seconds of total database time, a higher-priority optimization target than a query that runs once per day at 1 second.
Profiling under production load. When the system runs at realistic load, CPU profiling with flamegraphs, memory profiling and I/O tracing show code-level hotspots that do not appear in development environments.
Teams can set up the monitoring infrastructure to check if scaling investments hit their targets once they grasp how reliability engineering principles apply to scaling. That lets them define SLOs for performance metrics as well as build the monitoring needed to scale.
A Practical Scaling Roadmap
For teams scaling from single-server beginnings:
Phase 1 (0-10K daily active users). This phase runs on a single application server and a single database. Code correctness and product-market fit come first here and premature optimization is waste.
Phase 2 (10K-100K daily active users). Get a load balancer and a second application server in place and put Redis in for session storage and basic caching. A read replica for the database should be added as well. File storage goes to S3 and basic auto-scaling gets set up.
Phase 3 (100K-1M daily active users). Put in a CDN for static assets. Broaden the caching approach. Get database queries optimized and put in the right indexes. Look at connection pooling. Move up vertical scaling of the database.
Phase 4 (1M-10M daily active users) Database read replicas should be evaluated. Asynchronous processing queues may be considered for heavy operations. Performance profiling should begin to find bottlenecks. Geographic distribution may be considered.
Phase 5 (10M+ daily active users). The database needs to be split up or moved to a distributed database. There will be multiple regions. A full CDN approach goes in place and advanced caching that is multi-layered and uses pre-computation. Different workload types get dedicated infrastructure.
Every phase deals with the actual current bottleneck instead of predicting what will bottleneck next. As the product grows, the architecture does too.
What Research and Industry Reports Show About Cloud Scaling
Cloud systems scaling draws on theoretical frameworks as well as empirically validated patterns that come from both academic and practitioner sources.
Martin Kleppmann's Designing Data-Intensive Applications (O'Reilly, 2017) is the definitive reference for scaling data systems.[1]
Kleppmann goes through the trade-offs between consistency, availability and partition tolerance (the CAP theorem, formalized by Eric Brewer in 2000) systematically and gives specific database and messaging patterns that make each trade-off clear.
Architects draw on the book's treatment of replication lag, partition strategies and distributed transactions as the conceptual vocabulary they need when they design systems at scale.
The AWS Well-Architected Framework's "Performance Efficiency" pillar (Amazon, continuously updated) provides Amazon's synthesized guidance from running the world's largest cloud platform.
Appropriate resource types should be selected by key recommendations (instance types should match workload characteristics). Resource choices need to be reviewed over time and monitoring is required to stay aware of how performance changes.
When systems get bigger, the system points to caching, autoscaling and architectural change as the main ways to keep efficiency.
Google's "Borg, Omega, and Kubernetes" paper (Brendan Burns, Brian Grant, David Oppenheimer, Eric Brewer, John Wilkes, ACM Queue, 2016) documented the decade-long evolution of Google's container orchestration systems.
Borg (Google's internal workload manager, 2003) managed hundreds of thousands of jobs across Google's infrastructure.
Google's cluster management system is described in the paper and it enabled the horizontal scaling of services such as Search, Maps and Gmail to handle billions of users.
Rachel Potvin and Josh Levenberg's "Why Google Stores Billions of Lines of Code in a Single Repository" (Communications of the ACM, 2016) describes how Google's monorepo and build system enable reliable horizontal scaling of development itself.
By ensuring that all code changes are validated against the full dependency graph, Google prevents scaling failures where component changes break downstream dependencies at scale.
Werner Vogels of Amazon explained in "Eventually Consistent" (Communications of the ACM, 2009) the practical meaning of the CAP theorem for scaling. That meaning is that distributed systems have to pick between consistency and availability when partitions occur.
When Vogels told the story of Amazon's design of Dynamo (its key-value store), the company put availability ahead of consistency by accepting stale reads in return for keeping its services running through network partitions. That trade-off lets Amazon scale horizontally its shopping cart and other high-availability services.
Twitter's engineering blog series (2012-2016) on infrastructure scaling documented the specific decisions made during Twitter's transformation from a monolithic Rails application to a distributed system.
Posts by Yao Yue and others covered the "Timeline Service" that cut database read load by 99% via materialized view precomputation. The "Firehose" service that let Twitter process its real-time data in real time.
Combined, these posts form a detailed case study of practical scaling choices working within real-world limits.
Real-World Case Studies in Cloud Scaling
Twitter's "Fail Whale" to Global Scale (2006-2012). From 2007 through 2012, Twitter had among the most public scaling failures any internet service has ever seen. Frequent outages hit the service as unpredictably as load spiked, especially during live events.
Vertical scaling alone was needed for a monolithic Ruby on Rails architecture that was the root cause. That required individual database servers and application servers that could not be scaled horizontally without redoing the architecture.
Twitter's engineering team documented their multi-year transformation in detailed blog posts.[8]
Decomposing the monolith into independent services (Timeline service, Tweet service and User service) and moving from MySQL to a mix of Cassandra (for storing the timeline) and MySQL (for user data) were the main changes.
Aggressive caching was put in place using Memcached and Redis and event-driven architecture with Kafka for data processing was adopted as well.
No sign of degradation was seen as of 2013 when Twitter went from failing under 10,000 concurrent users to handling traffic spikes of 150,000+ tweets per second during major events like the Super Bowl and World Cup.
Instagram's PostgreSQL Sharding at Scale. In 2012, Instagram (founded in 2010 and acquired by Facebook in 2012) wrote "Sharding & IDs at Instagram" for the Instagram Engineering Blog. That documented how the company scaled its database. Scaling from zero to 13 million users within their first year called for rapid scaling choices.
Over NoSQL options, Instagram went with PostgreSQL that had horizontal sharding and it put in place a sharding strategy based on user ID. Every shard contains a predictable slice of data that lets queries route deterministically without any cross-shard joins for the main use cases.
Designed for growth, the shard count started out with 512 logical shards spread across 12 physical servers and allowed the physical shard count to increase without having to reorganize logical shards. This method has become the reference implementation most widely adopted by PostgreSQL sharding.
Netflix's Global Auto-Scaling: Netflix's engineering team (Gregory Leclercq, Andrew Plavocos) documented their auto-scaling architecture in multiple AWS re:Invent presentations (2016-2022).
Instead of adding capacity only after load rises, Netflix uses a predictive approach to auto-scaling. Historical traffic patterns get modeled by them to pre-scale ahead of demand peaks that are predicted.
Netflix can predict traffic growth curves accurately for regularly scheduled content releases such as new episodes of popular series and can put in place infrastructure hours ahead of when the load arrives.
About 30 percent less idle capacity means big cost savings across their global fleet and auto-scaling reduces over-provisioning (idle capacity) by around 30 percent compared to static provisioning.
DoorDash's Meal-Time Scaling. Every day follows the same pattern for DoorDash (founded 2013). There are sharp spikes at lunch and dinner but the utilization is low in between meals.
Engineering documented its team's approach of using AWS scheduled scaling (scaling to particular capacities at set times) together with reactive auto-scaling to handle demand that was unpredictable.
Eliminating the latency between demand going up and more capacity being added was possible through pre-scheduling capacity for meal-time peaks and that was something reactive auto-scaling could not do.
Automatic addition of new worker instances kept driver matching latency low through peak periods and DoorDash put queue-based scaling in place for its driver dispatch workers too. The longer the queue of pending deliveries grew, the more new worker instances were added automatically.
Pinterest's Redis Caching Architecture: Pinterest's engineering team documented their caching architecture in "Scaling Pinterest" (InfoQ, 2013) and subsequent blog posts.
Hundreds of billions of pin impressions per month come out of a relatively small database footprint on Pinterest and that is achieved by using aggressive Redis caching.
They made their main architectural choice by caching the social graph (follower/following relationships) as well as home feed content in Redis. Read requests go through the cache and can be answered in microseconds instead of the milliseconds that database queries need.
About 95% of read traffic goes through the Redis layer and the PostgreSQL database deals mainly with writes as well as cache misses. Pinterest was able to scale to hundreds of millions of users using this architecture without having to grow its database infrastructure proportionally.
Amazon Aurora's Global Scaling: Amazon's Aurora database (launched 2014) was designed to solve the horizontal scaling problem for relational databases within AWS. Aurora separates compute from storage, replicating data across six storage nodes in three availability zones automatically.
Without any operational overhead, up to 15 read replicas can be added and removed and horizontal scaling of read capacity keeps the SQL interface intact.
Amazon's re:Invent 2019 presentation on Aurora Global Database showed that Aurora customers achieved peak throughputs of 600,000 reads per second and 200,000 writes per second on a single Aurora cluster: throughputs that would require dozens of independently sharded MySQL instances to achieve otherwise.
Cloudflare's Edge Computing at 300+ Locations: Cloudflare's network spans more than 300 cities globally, with each location running Cloudflare Workers (edge computing) alongside CDN caching.
Instead of scaling up a central origin server to deal with global traffic as is done in the conventional model, computation gets spread out to edge locations close to users in this architecture.
Cloudflare has documented serving over 50 million HTTP requests per second from this distributed architecture and global median response times come in under 50ms.
Developers can use the Workers platform to run JavaScript and WebAssembly at the edge. This creates a new scaling category where computation goes to the user instead of users connecting to central compute.
Key Metrics and Evidence for Cloud Scaling
Auto-scaling efficiency benchmarks. Auto-scaling brought a 25 to 40 percent cut in what it costs to run EC2s compared with setting up servers at full peak capacity. The same level of availability that AWS said in its 2022 architecture guidance.
Savings come from getting rid of idle over-provisioned capacity during times when traffic is low. When services have 10:1 peak-to-trough traffic ratios (that is common for consumer-facing apps), auto-scaling can cut 90% of the cost of that idle capacity.
Caching hit rate impact. The effect of caching on performance depends on the hit rate. At a hit rate of 95 percent, the system reduces database calls by 95 percent. A hit rate of 99 percent brings down database calls by 99 percent.
In a 2019 blog post, Stripe's engineering team documented that its Redis caching layer cut the load on PostgreSQL queries by 92%. That allowed them to keep database performance up through much lower cost of database infrastructure as user numbers grew.
Database connection pooling impact: Percona's benchmarks (2022) for PgBouncer (PostgreSQL connection pooler) showed that pooling 10,000 application connections through 100 actual database connections reduced database connection overhead by 99%.
Connection state database memory use fell from 30 to 50GB (10,000 connections at 3 to 5MB each) to 300 to 500MB (100 connections). That got rid of connection exhaustion as a scaling bottleneck that had needed vertical scaling of database servers before.
CDN offload ratios. The 2023 "State of the Internet" report from Akamai shows that companies using CDN for static as well as semi-static content got origin offload rates of 85 to 95%.
When a service gets 90% offload and handles 1 million requests daily, it sends only 100,000 from origin infrastructure and that is a 10x drop in origin load. The result is smaller, less costly origin fleets that still give performance to users worldwide.
Horizontal vs. vertical scaling cost curves. Linear vertical scaling by doubling CPU and memory gives sub-linear performance gain as shown by AWS pricing data. On a CPU-bound workload, doubling instance size most often brings in 1.6 to 1.8 times throughput improvement rather than 2 times. Of memory bandwidth, the bus and overhead from the operating system.
Horizontal scaling (doubling instance count) produces linear throughput improvement for stateless workloads.
At different points for different workload types, the crossover point comes where horizontal scaling becomes more cost-effective than vertical scaling. Stateless web application tiers have horizontal scaling almost universally preferred above a few hundred concurrent users.
Sharding complexity cost. The operational cost of database sharding is documented in Instagram's engineering blog from 2019. Engineers put in about 20% more time on database-related development work than they do for non-sharded systems.
Cross-shard query limits as well as the mental work needed to route traffic through sharding are what make this necessary.
Only when simpler scaling approaches such as vertical scaling, read replicas and caching fall short does this cost get justified. Delaying sharding as long as possible by first making simpler strategies as effective as possible is the blog's advice.
Sources & Further Reading
- Kleppmann, Martin. Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems. O'Reilly Media, 2017.
- Abbott, Martin and Fisher, Michael. The Art of Scalability: Scalable Web Architecture, Processes, and Organizations for the Modern Enterprise, 2nd ed. Addison-Wesley, 2015.
- Newman, Sam. Building Microservices: Designing Fine-Grained Systems, 2nd ed. O'Reilly Media, 2021.
- Richardson, Chris. Microservices Patterns: With Examples in Java. Manning Publications, 2018.
- Amazon Web Services. "Auto Scaling Documentation." docs.aws.amazon.com.
- Redis. "Redis Documentation." redis.io.
- Kafka. "Apache Kafka Documentation." kafka.apache.org. View source
- Twitter Engineering Blog. "The Infrastructure Behind Twitter: Scale." blog.twitter.com.
- Pinterest Engineering. "Building Pinterest's Analytics Platform." medium.com/pinterest-engineering.
- . "Real Life Architectures." highscalability.com.








