LSLínguas Sem BenaventeInglês para brasileiros

Aula

Performance deep dive

Nível: B2

Objetivo

Diagnosticar problemas de performance em inglês usando o vocabulário de profiling, caching, concurrency, resource contention, benchmark e regression, e apresentar um plano de correção estruturado (root cause, action items, owners, timeline) em design reviews, performance reviews e post-mortems.

Explicação

Em B2, discutir performance deixa de ser `the system is slow` e passa a descrever um diagnóstico estruturado: onde está o gargalo, qual evidência comprova, qual é a compensação aceita e como o time vai medir o ganho. O nome do processo é performance deep dive, e ele é o oposto de chute: cada afirmação tem que vir com dado.

1. Profiling: onde o tempo está indo

Profiling é a captura de onde o código gasta tempo (CPU, allocs, I/O). O resultado típico é um hot path: uma função ou um trecho que consome a maior parte do tempo total. Em B2, espera-se a distinção:

  • CPU-bound = o processador é o gargalo (cálculo, serialização, regex em loop).
  • I/O-bound = o processador está ocioso esperando rede, disco ou banco (leituras, chamadas externas).
  • Memory-bound = a pressão vem de alocação e coleta de lixo (GC pressure, allocs).

Frases-chave: *The profile shows the hot path in the JSON serializer*, *I/O dominates the request*, *we are CPU-bound on the export endpoint*.

2. Caching strategy: hit, miss e invalidação

Caching é a estratégia mais barata de melhorar latência, mas não é grátis. Os números que importam:

  • Cache hit ratio = fração de leituras que voltam do cache. *A 95% hit ratio is what we're aiming for.*
  • Cache miss = leitura que não estava no cache e foi ao backend.
  • Cache stampede = muitas requisições que sofreram miss ao mesmo tempo e derrubaram o backend (também chamado de *thundering herd*).
  • TTL (time to live) e invalidation definem por quanto tempo o cache vale e quando ele é descartado.

A frase típica de defesa: *The trade-off is short TTL, which means fresher data, versus long TTL, which means higher hit ratio. I'd defend a five-minute TTL with explicit invalidation on write.*

3. Concurrency e resource contention

Concurrency é executar mais trabalho em paralelo. Os problemas aparecem quando todos os fluxos disputam o mesmo recurso:

  • Lock contention = threads esperando o mesmo lock. *Lock contention on the inventory lock spiked at 4 p.m.*
  • Thread pool saturation = o pool de threads está cheio e novas tarefas ficam na fila.
  • Connection pool exhaustion = o pool de conexões do banco acabou, e o serviço entra em fila. *The pool is sized at 50, and we hit the ceiling under peak load.*
  • Queue depth = tamanho da fila aguardando processamento. *Queue depth crossed 10,000 at 16:02.*

A frase de diagnóstico: *We're not CPU-bound; we're contention-bound on the database connection pool.*

4. Benchmark e regression

Um benchmark é uma medição controlada de performance. Em B2 profissional, o benchmark não é só `requests per second`; ele sempre reporta percentis:

  • p50 (mediana) = a experiência típica.
  • p95 / p99 = a cauda, onde mora o sofrimento do usuário.

A frase típica: *p95 latency went from 120ms to 410ms, and p99 crossed 1.2s.*

Regression é quando uma métrica de performance piora entre duas versões. *This commit introduced a 3x regression in p99.* A defesa profissional cita o baseline (número anterior) e o delta (quanto piorou): *The p99 baseline was 380ms; we're now at 1.1s, a 3x regression in tail latency.*

5. Apresentar o diagnóstico e o plano

Um performance deep dive fechado tem quatro peças:

  1. Root cause = a causa raiz, não o sintoma. *The root cause is cache stampede on the inventory key when it expires.*
  2. Evidence = dado que comprova. *Queue depth crossed 10k; p99 went from 380ms to 1.1s.*
  3. Action items = o que cada pessoa vai fazer, com owner e timeline. *Daniel owns the connection pool resize, due Friday.*
  4. Success metric = como vamos saber que melhorou. *We define success as p99 under 500ms for 7 consecutive days.*

A frase de fechamento: *Given the data, I'd recommend a two-week plan: short-term mitigation this week, structural fix next sprint, with p99 under 500ms as the success metric.*

Exemplos

InglêsTraduçãoObservação
The profile shows the hot path in the JSON serializer, which accounts for 62% of CPU time.O profile mostra o hot path no serializador de JSON, que consome 62% do tempo de CPU.Profile + hot path + percent of CPU time: triade clássica do diagnóstico.
We are CPU-bound on the export endpoint, not I/O-bound.Estamos CPU-bound no endpoint de export, não I/O-bound.CPU-bound vs I/O-bound é a primeira bifurcação do diagnóstico.
A 95% cache hit ratio is what we're aiming for; we're at 71% today.Miramos 95% de cache hit ratio; hoje estamos em 71%.Hit ratio mede o ganho da estratégia de cache.
When the inventory key expires, we get a cache stampede that drops the backend for 30 seconds.Quando a chave de inventário expira, temos um cache stampede que derruba o backend por 30 segundos.Cache stampede = muitas requisições com miss ao mesmo tempo.
Lock contention on the inventory lock spiked at 4 p.m., and thread pool saturation followed within minutes.Lock contention no lock de inventário subiu às 16h, e a saturação do thread pool veio em seguida.Lock contention e thread pool saturation são pares frequentes em contenção.
The connection pool is sized at 50, and we hit the ceiling under peak load.O connection pool está dimensionado em 50, e batemos no teto sob carga de pico.Connection pool exhaustion é a causa clássica de fila no banco.
p95 latency went from 120ms to 410ms, and p99 crossed 1.2 seconds.A latência p95 foi de 120ms para 410ms, e o p99 passou de 1,2 segundo.Percentis importam mais que a média para用户体验.
The p99 baseline was 380ms; we're now at 1.1 seconds, a 3x regression in tail latency.O baseline de p99 era 380ms; hoje estamos em 1,1 segundo, uma regressão de 3x na cauda.Baseline + delta = a forma profissional de reportar regression.
The root cause is cache stampede on the inventory key, not the database itself.A causa raiz é cache stampede na chave de inventário, não o banco em si.Root cause separa causa de sintoma; o banco é o sintoma aqui.
Daniel owns the connection pool resize, due Friday; Priya owns the cache fix, due next sprint.Daniel é responsável pelo resize do connection pool, para sexta; Priya é responsável pelo fix do cache, para o próximo sprint.Owner + due date transforma recomendação em plano executável.

Erros comuns

  • Confundir profile com log: profile mede onde o tempo foi gasto; log conta o que aconteceu. O diagnóstico de performance começa com profile, não com log.
  • Dizer `the system is slow` sem percentil: em B2, sempre cite p95 ou p99; `it's slow` não é ação. Use `p99 crossed 1.2s` em vez de `users are complaining`.
  • Tratar hit ratio e hit count como sinônimos: hit ratio é fração (%), hit count é o número absoluto. Um hit count alto pode esconder um hit ratio baixo se o tráfego também subiu.
  • Misturar cache stampede com cache miss simples: miss é uma leitura que passou do cache; stampede é um evento coordenado de muitos misses ao mesmo tempo que derruba o backend.
  • Esquecer que TTL longo não é de graça: TTL longo aumenta hit ratio, mas aceita dados mais velhos. Em B2, sempre acompanhe TTL com explicit invalidation on write.
  • Confundir concurrency com parallelism: concurrency é estruturar tarefas para progredirem juntas; parallelism é executá-las literalmente ao mesmo tempo em múltiplos cores.
  • Dizer `the connection pool is full` como causa: `full` é sintoma. A causa pode ser connection leak, queries lentas, ou pico de tráfego. Em B2, nomeie a causa.
  • Apresentar plano sem owner ou timeline: `we should fix the cache` é opinião; `Priya owns the cache fix, due next sprint` é plano. Sem owner e due date, o plano não executa.
  • Esquecer o success metric: sem `p99 under 500ms for 7 days`, não há como saber se o plano funcionou. Em B2, o success metric fecha a apresentação.

Prática guiada

Reescreva cada bloco seguindo o padrão evidence → root cause → action items → success metric.

  1. De sintoma a dado
  2. `The system is slow.` → `p99 latency crossed 1.2 seconds during peak, and queue depth went above 10,000.`

  1. De sintoma a causa raiz
  2. `The database is slow.` → `The root cause is cache stampede on the inventory key, not the database itself; the database is the symptom.`

  1. De opinião a ação
  2. `We should fix the cache.` → `Priya owns the cache stampede fix, due next sprint; Daniel owns the connection pool resize, due Friday.`

  1. De esforço a métrica de sucesso
  2. `We will work on performance.` → `We define success as p99 under 500ms for 7 consecutive days, with a 95% cache hit ratio.`

Repare que cada frase carrega um número, um verbo de ação e uma consequência — é isso que transforma opinião em plano executável.

Resumo

Um performance deep dive em B2 é um diagnóstico estruturado: começa com profiling (CPU-bound vs I/O-bound vs memory-bound) para identificar o hot path, segue para a caching strategy (hit ratio, TTL, invalidation, stampede), passa por concurrency e resource contention (lock contention, thread pool, connection pool, queue depth), e fecha com benchmark (p50, p95, p99) e regression (baseline + delta). A apresentação segue quatro peças: root cause (a causa, não o sintoma), evidence (dado que comprova), action items (com owner e timeline) e success metric (o número que define vitória). Em performance review, sempre cite percentis, nunca a média; sempre cite owner, nunca `we should`; sempre cite baseline e delta, nunca `it's worse than before`.

Vocabulário

Palavras principais

18 itens
performance deep diveanálise aprofundada de performance

We scheduled a performance deep dive for the checkout endpoint.

Agendamos um performance deep dive para o endpoint de checkout.
profileprofile (captura de onde o tempo é gasto)

The profile shows the hot path in the serializer.

O profile mostra o hot path no serializador.
profilerferramenta de profiling

We attached a profiler to the production worker for ten minutes.

Anexamos um profiler ao worker de produção por dez minutos.
hot pathtrecho do código que consome mais tempo

The hot path is in the JSON serializer.

O hot path está no serializador de JSON.
CPU-boundlimitado pelo processador

The export endpoint is CPU-bound, not I/O-bound.

O endpoint de export é CPU-bound, não I/O-bound.
I/O-boundlimitado por entrada/saída (rede, disco, banco)

We're I/O-bound on the database calls.

Estamos I/O-bound nas chamadas de banco.
cachecache

We added a cache in front of the inventory lookup.

Adicionamos um cache na frente da consulta de inventário.
caching strategyestratégia de cache

Our caching strategy is read-through with a five-minute TTL.

Nossa estratégia de cache é read-through com TTL de cinco minutos.
cache hit ratiotaxa de acerto do cache

Our cache hit ratio is at 71%; we aim for 95%.

Nosso cache hit ratio está em 71%; miramos 95%.
cache misserro de cache (leitura que passou do cache)

Cache miss rate doubled after the deploy.

A taxa de cache miss dobrou após o deploy.
cache stampedequeda coordenada do backend por muitos misses simultâneos

A cache stampede on the inventory key dropped the backend for 30 seconds.

Um cache stampede na chave de inventário derrubou o backend por 30 segundos.
TTL (time to live)tempo de vida do cache

We set the TTL to five minutes and add explicit invalidation on write.

Definimos o TTL em cinco minutos e adicionamos invalidação explícita na escrita.
invalidationinvalidação (descarte explícito do cache)

We trigger cache invalidation on every write to the inventory key.

Disparamos invalidação de cache em cada escrita na chave de inventário.
concurrencyconcorrência

We increased concurrency by raising the thread pool size.

Aumentamos a concorrência elevando o tamanho do thread pool.
contentioncontenção (disputa por recurso compartilhado)

Lock contention spiked at 4 p.m.

Lock contention subiu às 16h.
lock contentioncontenção de lock (threads esperando o mesmo lock)

Lock contention on the inventory lock is the bottleneck.

Lock contention no lock de inventário é o gargalo.
thread poolpool de threads

The thread pool is sized at 200 workers.

O thread pool está dimensionado em 200 workers.
connection poolpool de conexões (de banco)

The connection pool is sized at 50; we hit the ceiling under peak.

O connection pool está dimensionado em 50; batemos no teto no pico.

História

História: Performance deep dive

Nível: B2

História em inglês

The alert at 4 p.m.

On Tuesday at 4:02 p.m., an alert fired on the checkout endpoint: p99 latency had crossed 1.2 seconds. Maya, the on-call engineer, opened the dashboard and saw that queue depth had climbed to 12,000 in less than three minutes. She paged the performance team and opened a war room, because the order volume was climbing toward Black Friday levels. The first question was the usual one: where is the time going?

Profiling the hot path

Maya attached a profiler to one of the checkout workers and captured a ten-minute sample. The profile ruled out CPU-bound and I/O-bound: the workers were mostly idle, waiting on something. What the profile did show was lock contention on the inventory lock, accounting for 71% of the wait time. Thread pool saturation followed almost immediately, because threads parked on the lock could not pick up new tasks. Maya noted that the lock was held longer than expected by a single function: a cache miss path on the inventory key.

Tracing the cache miss

She dug into the cache hit ratio for the inventory key, and the number told the rest of the story. The cache hit ratio had dropped from 95% to 71% after a config change the previous afternoon. The TTL had been lowered from five minutes to thirty seconds to fix a freshness bug, but the new TTL was too short for the traffic pattern. Every thirty seconds, the inventory key expired, and within milliseconds a small stampede of requests hit the backend. Each of those requests took the inventory lock while it recomputed the value, and the lock held for 80 to 200 milliseconds each time.

Benchmarking the candidate fixes

By 5 p.m., Maya and Tomás had three candidate fixes on the table. Option A was to raise the TTL back to five minutes, accepting slightly stale inventory data. Option B was to keep the short TTL and add a single-flight pattern, so only one request recomputes while others wait. Option C was to remove the inventory lock entirely and rely on atomic writes to the cache. They ran a benchmark at 2x the current load, and the numbers separated the options clearly. Option A kept p99 at 420ms but introduced a 4-second window of stale data, which the warehouse team flagged as a compliance risk. Option C pushed p99 down to 90ms, but it required a cache library upgrade the team had not scheduled.

Presenting the plan

On Wednesday morning, Maya presented the plan to the engineering leads with a single slide. The slide opened with the root cause: cache stampede on the inventory key, amplified by lock contention on the recompute path. The evidence was concrete: p99 baseline 380ms, current 1.2 seconds, cache hit ratio 71%, queue depth 12,000. Maya recommended Option B for this week, with Option C planned for the next sprint, because the upgrade window was already on the roadmap. The action items were explicit: Tomás owns the single-flight fix, due Friday; Daniel owns the upgrade dependency, due next sprint; Maya owns the postmortem, due the following Monday. She closed the slide with a success metric: p99 under 500ms for 7 consecutive days, and a cache hit ratio above 90%. The leads approved the plan in less than ten minutes, because the diagnosis, the evidence, and the owner of every step were already on the page.

Tradução linha por linha

InglêsTradução
On Tuesday at 4:02 p.m., an alert fired on the checkout endpoint: p99 latency had crossed 1.2 seconds.Na terça-feira às 16h02, um alerta disparou no endpoint de checkout: a latência p99 havia passado de 1,2 segundo.
Maya, the on-call engineer, opened the dashboard and saw that queue depth had climbed to 12,000 in less than three minutes.Maya, a engenheira de plantão, abriu o painel e viu que a queue depth havia subido para 12.000 em menos de três minutos.
She paged the performance team and opened a war room, because the order volume was climbing toward Black Friday levels.Ela acionou o time de performance e abriu uma war room, porque o volume de pedidos estava subindo para níveis de Black Friday.
The first question was the usual one: where is the time going?A primeira pergunta foi a de sempre: onde o tempo está indo?
Maya attached a profiler to one of the checkout workers and captured a ten-minute sample.Maya anexou um profiler a um dos workers de checkout e capturou uma amostra de dez minutos.
The profile ruled out CPU-bound and I/O-bound: the workers were mostly idle, waiting on something.O profile descartou CPU-bound e I/O-bound: os workers estavam quase ociosos, esperando algo.
What the profile did show was lock contention on the inventory lock, accounting for 71% of the wait time.O que o profile mostrou foi lock contention no lock de inventário, responsável por 71% do tempo de espera.
Thread pool saturation followed almost immediately, because threads parked on the lock could not pick up new tasks.A saturação do thread pool veio quase em seguida, porque threads paradas no lock não conseguiam pegar novas tarefas.
Maya noted that the lock was held longer than expected by a single function: a cache miss path on the inventory key.Maya percebeu que o lock estava sendo segurado por mais tempo do que o esperado por uma única função: um caminho de cache miss na chave de inventário.
She dug into the cache hit ratio for the inventory key, and the number told the rest of the story.Ela investigou o cache hit ratio da chave de inventário, e o número contou o resto da história.
The cache hit ratio had dropped from 95% to 71% after a config change the previous afternoon.O cache hit ratio havia caído de 95% para 71% depois de uma mudança de config na tarde anterior.
The TTL had been lowered from five minutes to thirty seconds to fix a freshness bug, but the new TTL was too short for the traffic pattern.O TTL havia sido reduzido de cinco minutos para trinta segundos para corrigir um bug de freshness, mas o novo TTL era curto demais para o padrão de tráfego.
Every thirty seconds, the inventory key expired, and within milliseconds a small stampede of requests hit the backend.A cada trinta segundos, a chave de inventário expirava, e em milissegundos um pequeno stampede de requisições atingia o backend.
Each of those requests took the inventory lock while it recomputed the value, and the lock held for 80 to 200 milliseconds each time.Cada uma dessas requisições pegava o lock de inventário enquanto recomputava o valor, e o lock ficava segurado de 80 a 200 milissegundos a cada vez.
By 5 p.m., Maya and Tomás had three candidate fixes on the table.Às 17h, Maya e Tomás tinham três correções candidatas na mesa.
Option A was to raise the TTL back to five minutes, accepting slightly stale inventory data.A opção A era elevar o TTL de volta para cinco minutos, aceitando dados de inventário ligeiramente desatualizados.
Option B was to keep the short TTL and add a single-flight pattern, so only one request recomputes while others wait.A opção B era manter o TTL curto e adicionar um padrão de single-flight, para que apenas uma requisição recomputasse enquanto as outras esperassem.
Option C was to remove the inventory lock entirely and rely on atomic writes to the cache.A opção C era remover o lock de inventário por completo e depender de escritas atômicas no cache.
They ran a benchmark at 2x the current load, and the numbers separated the options clearly.Rodaram um benchmark com 2x da carga atual, e os números separaram as opções com clareza.
Option A kept p99 at 420ms but introduced a 4-second window of stale data, which the warehouse team flagged as a compliance risk.A opção A manteve o p99 em 420ms, mas introduziu uma janela de 4 segundos de dados desatualizados, que o time de warehouse apontou como risco de compliance.
Option C pushed p99 down to 90ms, but it required a cache library upgrade the team had not scheduled.A opção C empurrou o p99 para 90ms, mas exigia um upgrade da biblioteca de cache que o time não havia agendado.
On Wednesday morning, Maya presented the plan to the engineering leads with a single slide.Na manhã de quarta-feira, Maya apresentou o plano aos líderes de engenharia com um único slide.
The slide opened with the root cause: cache stampede on the inventory key, amplified by lock contention on the recompute path.O slide abriu com a causa raiz: cache stampede na chave de inventário, amplificado por lock contention no caminho de recompute.
The evidence was concrete: p99 baseline 380ms, current 1.2 seconds, cache hit ratio 71%, queue depth 12,000.A evidência era concreta: p99 baseline 380ms, atual 1,2 segundo, cache hit ratio 71%, queue depth 12.000.
Maya recommended Option B for this week, with Option C planned for the next sprint, because the upgrade window was already on the roadmap.Maya recomendou a opção B para esta semana, com a opção C planejada para o próximo sprint, porque a janela de upgrade já estava no roadmap.
The action items were explicit: Tomás owns the single-flight fix, due Friday; Daniel owns the upgrade dependency, due next sprint; Maya owns the postmortem, due the following Monday.Os action items foram explícitos: Tomás é responsável pelo fix de single-flight, para sexta; Daniel é responsável pela dependência de upgrade, para o próximo sprint; Maya é responsável pelo postmortem, para a segunda seguinte.
She closed the slide with a success metric: p99 under 500ms for 7 consecutive days, and a cache hit ratio above 90%.Ela fechou o slide com uma métrica de sucesso: p99 abaixo de 500ms por 7 dias consecutivos, e cache hit ratio acima de 90%.
The leads approved the plan in less than ten minutes, because the diagnosis, the evidence, and the owner of every step were already on the page.Os líderes aprovaram o plano em menos de dez minutos, porque o diagnóstico, a evidência e o responsável por cada passo já estavam na página.

Notas de vocabulário

  • p99 latency had crossed 1.2 seconds = p99 é o percentil 99; cruzar um limite em p99 sinaliza degradação séria da cauda
  • queue depth had climbed to 12,000 = queue depth é o tamanho da fila; cruzar a casa dos milhares indica saturação
  • The profile ruled out CPU-bound and I/O-bound = profile + ruling out = o processo de eliminar hipóteses antes de cravar a causa
  • lock contention on the inventory lock = lock contention aparece quando threads disputam o mesmo lock; medido em % do wait time
  • thread pool saturation = saturation = todas as threads ocupadas, sem margem para novas tarefas
  • cache hit ratio had dropped from 95% to 71% = queda de hit ratio após mudança de config é a evidência que costura o diagnóstico
  • a small stampede of requests hit the backend = cache stampede: muitos misses simultâneos após expirar uma chave quente
  • single-flight pattern = padrão em que apenas uma requisição recomputa enquanto as outras esperam; evita stampede
  • p99 baseline 380ms, current 1.2 seconds = baseline + atual = o formato profissional de reportar regression
  • owner + due date (Tomás owns..., due Friday) = owner + due date é o que transforma recomendação em plano executável
  • success metric: p99 under 500ms for 7 consecutive days = success metric fecha o plano: número + limite + janela de observação

Perguntas de compreensão

  1. What alert fired at 4:02 p.m. on Tuesday?
  2. What did Maya see when she opened the dashboard?
  3. What did the profile rule out?
  4. What was the dominant wait time in the profile?
  5. Why had the cache hit ratio dropped?
  6. What was a cache stampede, in Maya's case?
  7. Why was Option C not the immediate recommendation?
  8. What plan did Maya present on Wednesday morning?
  9. Who owns the single-flight fix, and when is it due?
  10. What was the success metric of the plan?

Prática com a história

  1. Reescreva como diagnóstico B2: `The workers are stuck.`
  2. Reescreva com baseline e delta: `Things are worse than before.`
  3. Reescreva atribuindo action items: `Someone needs to fix the cache and resize the pool.`
  4. Reescreva com success metric: `We will make the system faster.`
  5. Reescreva antecipando o contra-argumento: `Use the single-flight fix.`

Prática

Exercícios e teste

Próxima etapa
7blocos de exercícios disponíveis neste tema
10questões de teste para revisar depois da aula

A próxima melhoria é transformar esses arquivos em perguntas com resposta no navegador. Por enquanto, esta página já organiza o estudo e permite seguir a aula inteira sem abrir os arquivos manualmente.