">
 

Your backend doesn't slow down. It falls off a cliff.

Iniciado por joomlamz, Ontem às 15:25

Respostas: 1   |   Visualizações: 10

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Olá, pessoal do **webmastersmz.com**!

Recentemente, deparei-me com uma discussão técnica muito pertinente sobre o comportamento da performance em backends: **"Your backend doesn't slow down. It falls off a cliff."** (O teu backend não fica lento. Ele cai de um precipício). Como especialista na área, achei o tema crucial para a nossa realidade em Moçambique, onde a otimização de recursos é vital.

### Análise Técnica: O "Efeito Precipício"

O ponto central do tópico é que, ao contrário do que muitos pensam, os sistemas não degradam a performance de forma linear — eles atingem um ponto de ruptura catastrófico. Aqui estão os pontos principais que devemos considerar:

1.  **A Ilusão da Escalabilidade:** Quando os recursos (CPU, RAM, conexões de banco de dados) estão abaixo da capacidade máxima, o sistema parece estar a voar. Contudo, quando o limite é atingido, não há uma "lenta transição". Ocorre o fenómeno do *queue saturation* (saturação de filas). As requisições começam a falhar, os *timeouts* disparam e o serviço cai abruptamente.
2.  **O Papel das Filas (Queues):** O texto enfatiza que o uso de filas mal configuradas pode ser uma armadilha. Elas mascaram o problema ao aceitar pedidos que o backend não consegue processar em tempo útil, criando um efeito "bola de neve" que eventualmente derruba toda a infraestrutura.
3.  **Circuit Breakers como Solução:** O uso de padrões como *Circuit Breakers* é essencial para evitar o efeito cascata. Se um serviço está a falhar, é preferível falhar rápido e de forma controlada do que manter o sistema em estado de paralisia.
4.  **Monitorização de Percentis:** O artigo alerta contra o foco excessivo na média (average latency). Devemos olhar para o P95 e P99, pois é aí que se escondem os sinais de que o "precipício" está próximo.

**O que acham, caros colegas?** Vocês já passaram por essa situação onde o sistema estava "perfeito" e, de repente, ficou inacessível devido a um pico de tráfego que pareceu insignificante? Quais ferramentas de monitorização vocês têm utilizado para detetar esses sinais de alerta antes da queda? Vamos discutir isto no nosso fórum!

***

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com. Estamos prontos para oferecer a infraestrutura robusta que o seu negócio precisa para evitar surpresas desagradáveis.

Your backend doesn't slow down. It falls off a cliff.



Tópico: Your backend doesn't slow down. It falls off a cliff.
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
Most of us run some version of the same backend: a load balancer, a couple of app servers, Redis in front of Postgres. It works on a normal day, so we assume it scales in a straight line. Twice the traffic, a bit slower. Ten times the traffic, slower still.

That's not what happens. I took that exact setup, gave it real-looking traffic, and turned the traffic up step by step. Here's what I found, including the mistake I made first.



The setup


An online store. Nothing fancy:

Users ──> Load balancer ──> 2 app servers ──> Redis (80% hits) ──> Postgres primary
│                                      ▲
└──────────── writes ──────────────────┘

•
Traffic: 250 requests a second at the evening peak.

•
Mix: 15% writes (carts, orders, payments), 30% product images, 55% reads.

•
Machines: two general-purpose app servers and one Postgres primary, all the smallest size on offer (AWS large), with Redis answering 80% of reads.

Then a creator with a big following posts a reel about the store. How far can this go?



First, my mistake


When I first drew it, I connected the app servers to Redis, and Redis to Postgres, and nothing else. It looked right. At 250 requests a second, with every machine under 10% busy, 15% of requests failed.

15% is exactly the writes. Redis was in front of Postgres for reads, but the app servers had no line to Postgres to save anything. Every cart update and every order had nowhere to go.

It's an obvious bug once you see it. It's also exactly the kind of bug a diagram never shows you, because a diagram doesn't send requests.

With that fixed (the app servers also write straight to Postgres), here's the real test.



Turning up the traffic


Traffic
Requests/sec
Failed
Slowest 1% (p99)
App servers busy
Postgres busy

Today
250
0%
84 ms
6%
7%

2x
500
0%
84 ms
12%
13%

10x
2,500
0%
92 ms
63%
67%

12x
3,000
0%
103 ms
75%
81%

14x
3,500
0%
156 ms
88%
94%

15x
3,750
0.4%
12.2 s
105%
126%

16x
4,000
6.6%
12.3 s
157%
101%

20x
5,000
35.7%
6.3 s
277%
86%

100x
25,000
100%
12.3 s
1,181%
0%

Look at the jump from 3,500 to 3,750. Seven percent more traffic, and the slowest 1% of requests go from 156 milliseconds to 12.2 seconds. Nearly 80 times slower.



Why it's a cliff, not a slope


A server isn't slow or fast. It has a queue. When it's 50% busy, a new request usually finds it free. When it's 94% busy, a new request almost always waits behind others, and the wait grows much faster than the load does. Past 100%, the queue never drains: every second, more arrives than leaves.

That's why "it's fine at 10x" tells you almost nothing about 15x. The useful number isn't how fast it is today. It's how busy the busiest part is, and how close that is to 100%.



Three things that surprised me




1. Redis was 2% busy


The cache wasn't the problem. It was barely working. At 3,500 requests a second, Redis sat at 2% while Postgres was at 94%.

Redis takes reads off Postgres, but only the hits. Every write still lands on Postgres, and so does every cache miss (20% of reads here). With 15% of all traffic being writes, the database fills up long before the cache notices anything.

If your plan for growth is "we have Redis", check what's actually reaching your database.



2. Retries tripled the traffic


At 100x, 25,000 users a second became 75,000 attempts a second. Requests time out, clients retry, and the retries pile on top of the real traffic. The load balancer, which had no problem with 25,000 a second, showed 150% busy, purely from retries.

Fix the app servers and the database, and the retries stop: attempts drop back to 25,000 and the load balancer to 50%. If you'd looked at the load balancer first, you'd have scaled the wrong thing.



3. Broken costs more than fixed


On AWS list prices:

• The failing design at 100x: $122,942 a month. With retries, each failed request is sent about three times, and you pay for every one.

• The fixed design at 100x: $47,687 a month.

• The fix itself: bigger app servers (large to 4xlarge) and a bigger Postgres (large to 4xlarge), $1,695 a month more in machines.

And at today's 250 requests a second, the machines cost $430 a month, but internet traffic costs $647. Serving product images from your own servers costs more than the servers. That's the real case for a CDN or object storage: the bill, not only the speed.



So what would I do with this store?


•
Know your cliff. Here it's about 3,500 requests a second, 14x today. A reel that brings 15x takes the store down.

•
Watch Postgres, not Redis. It hits the wall first. A bigger primary moves the cliff; read replicas and a queue for writes move it further.

•
Get images off the app servers. It's the biggest line on the bill at today's traffic.

•
Retry with backoff. Otherwise a slow minute turns into three times the traffic.



How I ran this


I build Bugpit, a browser game for learning system design: you build a backend from blocks, send traffic at it and watch it break. This week I added Test my app: build the backend you actually run, set your real traffic, and it shows today, 2x, 10x and 100x, with what breaks first, the monthly bill, and the cheapest fix with its price. It also found my wiring mistake above and said so, instead of telling me to buy bigger servers.

You can copy the result as a one-page review (diagram, table, fixes) to paste into Slack, Notion or a pull request.

To be clear about what it is: a model, not a load test. Prices come from AWS list prices, and anything without a source is marked as an estimate. Your Postgres with your queries will differ. But it's a quick way to find out roughly where your cliff is, before a reel finds it for you.

What's the biggest spike your app has taken, and what broke first?


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: