Escalar é fazer um sistema aguentar mais carga sem cair. Como dev sênior, você precisa não só conhecer as estratégias, mas explicar seus trade-offs e identificar o gargalo real — que quase nunca é a aplicação. Esse é um dos temas centrais de entrevistas de system design.
Vertical vs horizontal
Há duas formas de escalar. Vertical (scale up) é colocar uma máquina maior: mais CPU, mais RAM. Horizontal (scale out) é colocar mais máquinas, dividindo a carga entre elas. A analogia: escalar vertical é trocar seu carro por um caminhão; escalar horizontal é comprar vários carros. Cada um resolve um tipo de problema.
| Aspecto | Vertical (scale up) | Horizontal (scale out) |
|---|---|---|
| Como | Máquina mais potente | Mais máquinas |
| Limite | Teto físico do hardware | Praticamente ilimitado |
| Complexidade | Baixa (não muda o código) | Maior (precisa coordenar) |
| Resiliência | Ponto único de falha | Uma máquina cai, outras seguem |
Por que stateless é a chave
Escalar horizontalmente só funciona bem se os serviços forem stateless: nenhuma requisição depende de qual máquina atendeu a anterior. Se o servidor guarda estado em memória (uma sessão, por exemplo), o usuário "preso" naquela máquina não pode ser atendido por outra. Por isso o estado vai para fora — um banco, um cache compartilhado como Redis. Com serviços stateless, adicionar máquinas é trivial.
Load balancer
Com várias instâncias, alguém precisa distribuir as requisições entre elas: o load balancer. Ele fica na frente, recebe todo o tráfego e o reparte:
+----------------+
clientes | Load Balancer |
---------> | (round-robin) |
+----------------+
/ | \
v v v
[App 1] [App 2] [App 3] <- instancias stateless
\ | /
v v v
+-------------------+
| Banco de dados | <- estado compartilhado
+-------------------+
A estratégia mais simples é round-robin: distribui as requisições em rodízio, uma para cada instância em sequência. Outras opções consideram qual instância está menos ocupada (least connections) ou a localização do usuário.
O banco como gargalo
Aqui está o ponto que separa juniores de seniores: você pode ter 50 instâncias da aplicação, mas se todas batem no mesmo banco, o banco vira o gargalo. A aplicação escala fácil; o estado, não. As saídas principais:
- Read replicas: cópias do banco que atendem só leituras, aliviando o banco principal (que fica com as escritas). Funciona bem quando há muito mais leitura que escrita.
- Sharding: particionar os dados entre vários bancos (ex.: usuários A-M num, N-Z noutro), distribuindo também as escritas — porém com grande aumento de complexidade.
Escalar a aplicação é a parte fácil; escalar o estado é a parte difícil. Quando alguém diz "é só subir mais servidores", pergunte: e o banco aguenta?
Trade-offs
Não existe almoço grátis. Horizontal traz resiliência e escala quase ilimitada, mas exige serviços stateless, load balancers e lida com a complexidade de sistemas distribuídos — incluindo decisões de consistência que aparecem no teorema CAP. Vertical é simples mas tem teto e é ponto único de falha. Na prática, sistemas maduros combinam os dois: escalam vertical até certo ponto e horizontal a partir daí.
Conclusão
Escalabilidade é sobre remover gargalos, não sobre adicionar máquinas cegamente. Mantenha serviços stateless, use um load balancer para distribuir carga e, sobretudo, lembre que o banco costuma ser o limite real. Saber onde está o gargalo e qual trade-off aceitar é exatamente o tipo de raciocínio esperado de um sênior.
Scaling means making a system handle more load without falling over. As a senior dev, you need not only to know the strategies, but to explain their trade-offs and identify the real bottleneck — which is almost never the application. This is one of the core topics in system design interviews.
Vertical vs horizontal
There are two ways to scale. Vertical (scale up) means getting a bigger machine: more CPU, more RAM. Horizontal (scale out) means adding more machines, splitting the load among them. The analogy: scaling vertically is swapping your car for a truck; scaling horizontally is buying several cars. Each solves a different kind of problem.
| Aspect | Vertical (scale up) | Horizontal (scale out) |
|---|---|---|
| How | More powerful machine | More machines |
| Limit | Physical hardware ceiling | Practically unlimited |
| Complexity | Low (no code changes) | Higher (needs coordination) |
| Resilience | Single point of failure | One machine goes down, the others keep going |
Why stateless is the key
Scaling horizontally only works well if the services are stateless: no request depends on which machine handled the previous one. If the server keeps state in memory (a session, for example), a user "stuck" on that machine can't be served by another. That's why state moves out — to a database, a shared cache like Redis. With stateless services, adding machines is trivial.
Load balancer
With multiple instances, someone has to distribute the requests among them: the load balancer. It sits in front, receives all the traffic and splits it up:
+----------------+
clients | Load Balancer |
---------> | (round-robin) |
+----------------+
/ | \
v v v
[App 1] [App 2] [App 3] <- stateless instances
\ | /
v v v
+-------------------+
| Database | <- shared state
+-------------------+
The simplest strategy is round-robin: requests are distributed in rotation, one to each instance in sequence. Other options take into account which instance is least busy (least connections) or the user's location.
The database as a bottleneck
Here's the point that separates juniors from seniors: you can have 50 instances of the application, but if they all hit the same database, the database becomes the bottleneck. The application scales easily; state doesn't. The main ways out:
- Read replicas: copies of the database that serve reads only, relieving the primary (which keeps the writes). Works well when there are far more reads than writes.
- Sharding: partitioning the data across several databases (e.g. users A-M in one, N-Z in another), which also spreads the writes — but with a big increase in complexity.
Scaling the application is the easy part; scaling the state is the hard part. When someone says "just spin up more servers", ask: can the database handle it?
Trade-offs
There's no free lunch. Horizontal scaling brings resilience and nearly unlimited scale, but requires stateless services, load balancers and deals with the complexity of distributed systems — including consistency decisions that show up in the CAP theorem. Vertical is simple but has a ceiling and is a single point of failure. In practice, mature systems combine both: they scale vertically up to a point and horizontally from there.
Conclusion
Scalability is about removing bottlenecks, not blindly adding machines. Keep services stateless, use a load balancer to distribute load and, above all, remember that the database is usually the real limit. Knowing where the bottleneck is and which trade-off to accept is exactly the kind of reasoning expected of a senior.