We improved observability by adding structured logs and a new latency metric.
Melhoramos a observabilidade adicionando logs estruturados e uma nova métrica de latência.Aula
Observability e logs
Nível: B1
Objetivo
Usar os termos centrais de observabilidade (metric, log, trace, alert, dashboard, latency, throughput) para descrever uma investigação de produção, seguindo o fluxo alert → dashboard → logs → trace → root cause.
Explicação
Em produção, observability é a capacidade de entender o que está acontecendo em um sistema a partir dos sinais que ele emite. Os três pilares clássicos são metrics, logs e traces; cada um responde a um tipo diferente de pergunta.
Metric é um número medido ao longo do tempo, leve e barato de armazenar: `The error rate spiked to 3% at 14:32.` Métricas são boas para ver tendências e detectar anomalias em um dashboard, mas não mostram o que aconteceu dentro de uma única requisição.
Log é um evento discreto com timestamp, nível (`info`, `warn`, `error`) e mensagem. Logs estruturados incluem campos como `trace_id` e `user_id`: `The auth service logged a 500 error with trace_id=abc123.` Logs são ótimos para encontrar uma mensagem de erro específica, mas o volume em produção é enorme, então normalmente é preciso filtrar por nível, serviço ou trace_id.
Trace é o caminho completo de uma requisição através de vários serviços, dividido em spans (trechos). Cada span registra onde o tempo foi gasto: `The trace shows that 1.1s out of 1.2s was spent in the payment service.` Traces são caros de gerar e guardar, então costumam ser amostrados (uma fração das requisições).
Dashboard é um painel que reúne várias métricas em gráficos; alert é uma regra que dispara quando uma métrica ultrapassa um limite (threshold): `We have an alert when the p95 latency exceeds 1 second.` Em geral, o alert não diz a causa; ele só avisa que algo está fora do esperado.
Latency é o tempo que uma requisição leva para completar. Em produção raramente se olha a média: o que importa é a cauda, ou seja, os percentis p50, p95 e p99 (o valor abaixo do qual 50%, 95% e 99% das requisições ficaram). Throughput é o volume de requisições por segundo (`requests per second` ou `RPS`).
Para descrever uma investigação de produção, siga um mini-roteiro: o sinal que disparou (`The alert fired at 14:32`), o que o dashboard mostrou (`The p95 latency jumped from 200ms to 1.2s`), o que os logs e traces indicaram (`A trace pointed to the payment service`), a causa raiz (`The root cause was a slow database query introduced in release 2.14`) e a mitigação (`We rolled back the release and the latency returned to baseline`). Repetir a estrutura `signal → dashboard → logs/traces → root cause → fix` torna a investigação fácil de entender em inglês, mesmo em uma call sob pressão.
Exemplos
| Inglês | Tradução | Observação |
|---|---|---|
| The p95 latency jumped from 200ms to 1.2s after the deploy. | A latência p95 subiu de 200ms para 1,2s depois do deploy. | P95 é um percentil; ele descreve a cauda, não a média. |
| The dashboard shows a spike in error rate at 14:32. | O dashboard mostra um pico de taxa de erro às 14h32. | Dashboard agrega métricas; cite a métrica e o horário. |
| I filtered the logs by error level and found a stack trace from the auth service. | Filtrei os logs por nível de erro e encontrei um stack trace do serviço de autenticação. | Filtrar por nível e por serviço reduz o volume de logs. |
| The trace shows that 1.1s out of 1.2s was spent in the payment service. | O trace mostra que 1,1s de 1,2s foram gastos no serviço de pagamento. | Trace decompõe o tempo total em spans por serviço. |
| We have an alert when the p95 latency exceeds 1 second for five minutes. | Temos um alerta quando a latência p95 passa de 1 segundo por cinco minutos. | Alert combina métrica, threshold e janela de tempo. |
| The throughput dropped to almost zero during the incident. | O throughput caiu para quase zero durante o incidente. | Throughput mede volume; queda brusca indica problema sério. |
| The root cause was a slow database query introduced in release 2.14. | A causa raiz foi uma query lenta de banco introduzida na release 2.14. | Root cause liga a falha ao deploy que a trouxe. |
Erros comuns
- Confundir latency e throughput: latency é tempo por requisição, throughput é volume de requisições; `latency high` e `throughput high` não significam a mesma coisa.
- Dizer 'the metric' sem nomear qual: sempre cite a métrica, como `p95 latency`, `error rate` ou `throughput`.
- Tratar 'log' (um evento) e 'logs' (o arquivo agregado) como a mesma coisa em frases plurais: `The log says...` vs. `The logs show...`.
- Misturar trace e log: trace mostra o caminho de uma requisição, log mostra um evento com timestamp; dizer `the log of the request` é vago.
- Usar 'alert' e 'alarm' como sinônimos: em observabilidade, alert é a regra/notificação; alarm é mais usado em监控系统 físicos e soa estranho em software.
- Descrever a investigação fora de ordem: começar pelo fix e só depois dizer o que o dashboard mostrou quebra o raciocínio; siga `signal → dashboard → logs/traces → root cause → fix`.
- Esquecer a unidade de tempo na latency: sempre inclua `ms` ou `s`; `latency 200` não é claro.
Prática guiada
Transforme cada nota solta em uma frase de investigação bem estruturada, na ordem `signal → dashboard → logs/traces → root cause → fix`:
- Nota solta: `alerta às 14h32, latência subiu, query lenta, fiz rollback.`
Em frase: `The latency alert fired at 14:32. The dashboard showed the p95 latency jumping from 200ms to 1.2s. A trace pointed to a slow database query in the payment service, and the logs confirmed the same query in the error stream. We identified that the query was introduced in release 2.14, so we rolled it back and the latency returned to baseline.`
- Nota solta: `throughput caiu para zero por dois minutos, parece timeout.`
Em frase: `The throughput alert fired when requests per second dropped to almost zero for two minutes. The dashboard showed a flat line on the API gateway, and the logs were full of upstream timeout errors. A trace showed the timeout happening in the auth service. The root cause was a stuck connection pool, which we restarted.`
Note como cada frase nomeia o sinal, a métrica do dashboard, o que os logs e traces indicaram e a causa raiz antes do fix.
Resumo
Os três pilares de observabilidade são metrics (números ao longo do tempo), logs (eventos discretos com contexto) e traces (caminho de uma requisição em spans). Dashboard reúne métricas; alert dispara quando uma métrica ultrapassa um threshold. Latency mede tempo por requisição (em ms ou s) e é vista por percentis (p50, p95, p99); throughput mede volume (RPS). Para descrever uma investigação, siga a ordem `signal → dashboard → logs/traces → root cause → fix`.
Vocabulário
Palavras principais
Latency p95 and error rate are the most important metrics for this service.
Latência p95 e taxa de erro são as métricas mais importantes para este serviço.Each log includes the trace_id so we can correlate events across services.
Cada log inclui o trace_id para correlacionar eventos entre serviços.The first error log entry appeared at 14:32:05.
A primeira entrada de log de erro apareceu às 14h32:05.The trace shows that 1.1s out of 1.2s was spent in the payment service.
O trace mostra que 1,1s de 1,2s foram gastos no serviço de pagamento.Each service creates its own span with a start time and duration.
Cada serviço cria seu próprio span com horário de início e duração.The on-call dashboard shows latency, error rate, and throughput on one screen.
O dashboard de plantão mostra latência, taxa de erro e throughput em uma tela.We have an alert when the p95 latency exceeds 1 second for five minutes.
Temos um alerta quando a latência p95 passa de 1 segundo por cinco minutos.The p95 latency for the checkout endpoint is 800ms.
A latência p95 do endpoint de checkout é 800ms.The service handled a peak throughput of 5,000 requests per second.
O serviço suportou um pico de throughput de 5.000 requisições por segundo.The error rate spiked from 0.1% to 3% during the incident.
A taxa de erro subiu de 0,1% para 3% durante o incidente.We monitor p99 latency, not the average, because the tail matters most.
Monitoramos a latência p99, não a média, porque a cauda é o que importa.We lowered the alert threshold for error rate from 5% to 1%.
Reduzimos o limite do alerta de taxa de erro de 5% para 1%.The incident lasted 18 minutes and affected 2% of requests.
O incidente durou 18 minutos e afetou 2% das requisições.After 30 minutes, we identified the root cause as a stuck connection pool.
Depois de 30 minutos, identificamos a causa raiz como um pool de conexões travado.Latency returned to baseline after the rollback.
A latência voltou ao baseline depois do rollback.We monitor latency, throughput, and error rate for every service.
Monitoramos latência, throughput e taxa de erro para cada serviço.The alert triggered when the error rate crossed 1% for two minutes.
O alerta disparou quando a taxa de erro passou de 1% por dois minutos.História
História: Observability e logs
Nível: B1
História em inglês
The alert that woke up the on-call
At 14:32 on Tuesday, a latency alert fired in the payments channel. The on-call engineer, Marco, acknowledged the alert within two minutes. He opened the on-call dashboard and saw that the p95 latency for the checkout endpoint had jumped from 200ms to 1.2s. The error rate had also spiked, from 0.1% to about 3%, but throughput was still close to normal. Marco wrote in the incident channel, "Alert fired at 14:32, p95 latency is 1.2s and error rate is around 3%. Opening the dashboard now."
From dashboard to logs and traces
Marco first checked the latency dashboard to confirm the spike was real and not a glitch in the metric pipeline. Then he filtered the logs by error level and found a stack trace pointing to the payment service. The first error log entry appeared at 14:32:05, almost at the same time as the alert. Marco pulled the trace for one failed request and saw that 1.1s out of 1.2s was spent in a single span inside the payment service. Inside that span, the trace showed a slow database query against the orders table. He shared the trace ID in the channel and wrote, "Slow span is in the payment service, looks like a DB query on the orders table."
Root cause and fix
A teammate checked the recent deploys and noticed that release 2.14 had shipped a new report query that joined the orders table with two other tables. "That query is missing an index," he said, "and it runs on the same connection pool as the checkout flow, so it slowed everything down." Marco replied, "So the root cause is the new report query from release 2.14, not a network issue. That matches what the trace showed." They decided to roll back the query behind a feature flag, so the checkout flow could recover without disabling the report. Within a few minutes, the p95 latency returned to baseline and the error rate dropped back below 0.2%. Marco closed the alert and wrote a short post-incident note: "Alert fired at 14:32, root cause was a missing index in release 2.14, mitigated by feature flag, latency back to baseline."
Tradução linha por linha
| Inglês | Tradução |
|---|---|
| At 14:32 on Tuesday, a latency alert fired in the payments channel. | Às 14h32 de terça-feira, um alerta de latência disparou no canal de pagamentos. |
| The on-call engineer, Marco, acknowledged the alert within two minutes. | O engenheiro de plantão, Marco, reconheceu o alerta em até dois minutos. |
| He opened the on-call dashboard and saw that the p95 latency for the checkout endpoint had jumped from 200ms to 1.2s. | Ele abriu o dashboard de plantão e viu que a latência p95 do endpoint de checkout tinha subido de 200ms para 1,2s. |
| The error rate had also spiked, from 0.1% to about 3%, but throughput was still close to normal. | A taxa de erro também tinha dado um pico, de 0,1% para cerca de 3%, mas o throughput continuava próximo do normal. |
| Marco wrote in the incident channel, "Alert fired at 14:32, p95 latency is 1.2s and error rate is around 3%. Opening the dashboard now." | Marco escreveu no canal do incidente: "Alerta disparou às 14h32, latência p95 está em 1,2s e taxa de erro em torno de 3%. Abrindo o dashboard agora." |
| Marco first checked the latency dashboard to confirm the spike was real and not a glitch in the metric pipeline. | Marco primeiro olhou o dashboard de latência para confirmar que o pico era real e não uma falha no pipeline de métricas. |
| Then he filtered the logs by error level and found a stack trace pointing to the payment service. | Depois ele filtrou os logs por nível de erro e encontrou um stack trace apontando para o serviço de pagamento. |
| The first error log entry appeared at 14:32:05, almost at the same time as the alert. | A primeira entrada de log de erro apareceu às 14h32:05, praticamente junto com o alerta. |
| Marco pulled the trace for one failed request and saw that 1.1s out of 1.2s was spent in a single span inside the payment service. | Marco puxou o trace de uma requisição com falha e viu que 1,1s de 1,2s foram gastos em um único span dentro do serviço de pagamento. |
| Inside that span, the trace showed a slow database query against the orders table. | Dentro daquele span, o trace mostrou uma query lenta contra a tabela de pedidos. |
| He shared the trace ID in the channel and wrote, "Slow span is in the payment service, looks like a DB query on the orders table." | Ele compartilhou o ID do trace no canal e escreveu: "O span lento está no serviço de pagamento, parece uma query de banco na tabela de pedidos." |
| A teammate checked the recent deploys and noticed that release 2.14 had shipped a new report query that joined the orders table with two other tables. | Um colega conferiu os deploys recentes e percebeu que a release 2.14 tinha subido uma query de relatório nova que fazia join da tabela de pedidos com outras duas tabelas. |
| "That query is missing an index," he said, "and it runs on the same connection pool as the checkout flow, so it slowed everything down." | "Essa query está sem índice", disse ele, "e roda no mesmo pool de conexões do fluxo de checkout, então atrasou tudo." |
| Marco replied, "So the root cause is the new report query from release 2.14, not a network issue. That matches what the trace showed." | Marco respondeu: "Então a causa raiz é a query de relatório nova da release 2.14, não um problema de rede. Isso bate com o que o trace mostrou." |
| They decided to roll back the query behind a feature flag, so the checkout flow could recover without disabling the report. | Eles decidiram voltar a query atrás de uma feature flag, para o fluxo de checkout se recuperar sem desabilitar o relatório. |
| Within a few minutes, the p95 latency returned to baseline and the error rate dropped back below 0.2%. | Em poucos minutos, a latência p95 voltou ao baseline e a taxa de erro caiu para menos de 0,2%. |
| Marco closed the alert and wrote a short post-incident note: "Alert fired at 14:32, root cause was a missing index in release 2.14, mitigated by feature flag, latency back to baseline." | Marco fechou o alerta e escreveu um post-incident curto: "Alerta disparou às 14h32, causa raiz foi um índice faltando na release 2.14, mitigado por feature flag, latência voltou ao baseline." |
Notas de vocabulário
- alert fired = alert disparou; fired é o verbo padrão para alerta que ativa
- on-call = de plantão; o engenheiro responsável por responder a alertas fora do horário
- p95 latency = percentil 95 da latência; valor abaixo do qual 95% das requisições ficaram
- throughput = volume de requisições por segundo; throughput normal com latência alta indica que cada requisição está lenta, não que o sistema parou
- error rate = porcentagem de requisições que retornaram erro; útil para diferenciar degradação de falha total
- log entry = uma única entrada dentro do arquivo de logs; geralmente inclui timestamp, nível e mensagem
- stack trace = rastro da pilha de chamadas; aparece em logs de erro e aponta para o módulo com problema
- trace ID = identificador único de um trace; usar em chat e tickets permite que outros engenheiros abram o mesmo trace
- span = trecho individual de um trace, normalmente associado a um serviço ou chamada
- root cause = causa raiz; motivo principal que provocou o incidente, geralmente ligado a um deploy ou mudança
- feature flag = chave que liga ou desliga uma feature em produção sem deploy; útil para mitigação rápida
- back to baseline = de volta ao valor normal; baseline é a referência saudável de uma métrica
Perguntas de compreensão
- What kind of alert fired at 14:32?
- What did Marco see when he opened the on-call dashboard?
- Was throughput also affected during the incident?
- How did Marco find the slow service in the system?
- What did the trace show inside the slow span?
- What was the root cause of the incident?
- Why did the team choose a feature flag instead of a full rollback of release 2.14?
- What evidence did Marco mention in the post-incident note?
Prática com a história
- Reescreva em uma frase única: 'alerta disparou às 14h32; dashboard mostrou p95 subindo de 200ms para 1,2s; trace apontou para o payment service.'
- Traduza: 'A causa raiz foi uma query lenta sem índice na release 2.14.'
- Reescreva em formato signal → root cause: 'alerta de throughput às 15h10; tudo voltou ao normal depois do feature flag.'
- Traduza: 'Filtrei os logs por nível de erro e encontrei um stack trace do serviço de autenticação.'
Prática
Exercícios e teste
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.