Book notes

Software engineering is programming over time.

A friendly walkthrough of Software Engineering at Google: what changes when code has to live for decades and teams have to grow.

A ideia centralThe core idea

O livro Software Engineering at Google (Titus Winters, Tom Manshreck e Hyrum Wright, O’Reilly, 2020) conta como o Google mantém uma base de código enorme viva por décadas. A frase que resume o livro inteiro é: engenharia de software é programação integrada ao longo do tempo.The book Software Engineering at Google (Titus Winters, Tom Manshreck and Hyrum Wright, O’Reilly, 2020) tells how Google keeps a huge codebase alive for decades. The sentence that sums up the whole book is: software engineering is programming integrated over time.

Programar é produzir código que funciona hoje. Fazer engenharia é produzir código que continue funcionando, e que ainda possa ser mudado com segurança, enquanto ele viver. O livro aponta três diferenças:Programming is producing code that works today. Engineering is producing code that keeps working, and can still be changed safely, for as long as it lives. The book points to three differences:

  • Tempo. Quanto tempo o código vai viver? A resposta razoável pode variar por um fator de 100.000, de minutos a décadas.Time. How long will the code live? A reasonable answer can vary by a factor of 100,000, from minutes to decades.
  • Escala. Tudo o que a organização faz várias vezes (revisar, testar, atualizar) precisa continuar viável quando ela crescer 10 ou 100 vezes.Scale. Everything the organization does repeatedly (review, test, upgrade) must stay viable when it grows 10 or 100 times.
  • Trade-offs. Decisões com custo e risco reais, tomadas com estimativas imprecisas. Vale justificar com razões, não com “porque eu mandei”.Trade-offs. Decisions with real cost and risk, made with imprecise estimates. Justify them with reasons, not with “because I said so”.
Código descartável: um script de uma tardeThrowaway code: an afternoon script horashours Código de longa vida: um sistema que a empresa mantém por décadasLong-lived code: a system the company maintains for decades décadasdecades pelo menos 100.000× de diferençaat least 100,000× apart
Quanto mais tempo o código vive, mais o mundo ao redor muda. Esta é a diferença entre programar e fazer engenharia.The longer code lives, the more the world around it changes. That is the difference between programming and engineering.

O livro chama de sustentável o projeto que, durante a vida esperada do código, é capaz de reagir a qualquer mudança valiosa (de tecnologia ou de produto). Repare: o que importa é a capacidade. Você pode escolher não atualizar uma biblioteca, mas precisa poder.The book calls a project sustainable when, for the code’s expected life span, it can react to any valuable change (technology or product). Note that what matters is the capability. You may choose not to upgrade a library, but you must be able to.

Uma frase para guardar: “é programação se ‘esperto’ é um elogio; é engenharia se ‘esperto’ é uma acusação.” Código esperto depende de detalhes frágeis; código de engenharia aposta em coisas que vão durar.A line to remember: “it’s programming if ‘clever’ is a compliment, but it’s software engineering if ‘clever’ is an accusation.” Clever code leans on fragile details; engineered code bets on things that will last.

Lei de HyrumHyrum’s Law

A lei diz: com usuários suficientes de uma API, não importa o que você prometeu no contrato; todo comportamento observável do seu sistema será usado por alguém.The law says: with a sufficient number of users of an API, it does not matter what you promise in the contract: all observable behaviors of your system will be depended on by somebody.

Um exemplo simplesA simple example

Imagine uma função listar_usuarios() documentada apenas como “devolve os usuários”. Na prática, ela devolve em ordem alfabética, porque o banco por acaso fazia isso. Ninguém prometeu a ordem, mas a tela de relatórios passou a contar com ela. Um dia você troca o banco, a ordem muda, e o relatório “quebra” sem que nenhuma regra escrita tenha sido violada. (Exemplo inventado para ilustrar.)Picture a function list_users() documented only as “returns the users”. In practice it returns them alphabetically, because the database happened to do so. Nobody promised the order, but the reports screen started relying on it. One day you swap the database, the order changes, and the report “breaks” although no written rule was violated. (An invented example, to illustrate.)

O que dá para observar (todo comportamento visível)What can be observed (every visible behavior) O que você prometeuWhat you promised (a documentação, o contrato)(the docs, the contract) “devolve a lista”“returns the list” a ordem dos itensthe order of items quanto tempo demorahow long it takes o texto exato do errothe exact error text campos extrasextra fields efeitos colateraisside effects Com usuários suficientes, alguém depende de cada ponto preto. Mudar qualquer um quebra alguém.With enough users, somebody depends on every black dot. Changing any of them breaks someone.
A Lei de Hyrum: o contrato é só o retângulo do meio. Os usuários dependem de tudo o que conseguem ver.Hyrum’s Law: the contract is only the middle rectangle. Users depend on everything they can see.

O exemplo do livro: ordem de um hashThe book’s example: hash ordering

Em muitas linguagens, percorrer um conjunto (set) devolve os itens numa ordem aparentemente aleatória. Todo especialista diz que não se pode contar com ela. Mas, com tempo suficiente, alguém contará. O livro lembra até que há quem use essa aleatoriedade como um gerador de números aleatórios ineficiente, e remover isso quebraria essas pessoas.In many languages, walking over a set returns items in a seemingly random order. Every expert says you must not rely on it. But given enough time, someone will. The book even notes that some code uses that randomness as an inefficient random-number generator, so removing it would break those users.

>>> for i in {"apple", "banana", "carrot", "durian", "eggplant"}: print(i)
durian
carrot
apple
eggplant
banana

O que fazer? Não dá para eliminar a Lei de Hyrum (como a entropia, ela sempre vale), mas dá para se planejar: ser claro sobre o que é promessa, tornar o não prometido difícil de usar (por exemplo, embaralhar de propósito) e ter testes que avisem quando algo muda.What to do? You cannot eliminate Hyrum’s Law (like entropy, it always applies), but you can plan for it: be clear about what is a promise, make the unpromised hard to rely on (for example, shuffling on purpose) and have tests that warn you when something changes.

Escala: políticas que funcionam quando a empresa cresceScale: policies that work as the company grows

O teste do livro para qualquer processo: imagine um engenheiro e faça a empresa crescer 10 ou 100 vezes. O trabalho dele cresce junto? Se cresce, o processo não escala, a não ser que haja automação.The book’s test for any process: picture one engineer and make the company grow 10 or 100 times. Does that engineer’s workload grow too? If it does, the process does not scale, unless there is automation.

tamanho da empresa (engenheiros, código, tempo)size of the company (engineers, code, time) trabalho por engenheirowork per engineer política que não escalapolicy that does not scale política que escalapolicy that scales
Pergunta de ouro: se a empresa for 10× maior, o trabalho de cada pessoa também vira 10×? Se sim, falta automação.The golden question: if the company is 10× bigger, does each person’s work become 10× too? If yes, you need automation.

Dois exemplos de política que não escalaTwo examples of policies that do not scale

  • Descontinuar assim: “vamos apagar o Widget antigo em 15 de agosto; migrem para o novo.” Com poucos times funciona. Com milhares, cada time gasta um tempo aprendendo a migrar, resolve só o seu caso e descarta o que aprendeu.Deprecating like this: “we’ll delete the old Widget on August 15; migrate to the new one.” With a few teams it works. With thousands, every team spends time learning to migrate, solves only its own case and throws the knowledge away.
  • Branches longas por time ou por feature: cada merge obriga todo mundo a ressincronizar e retestar. Com 5 a 10 branches dá para viver; com centenas, o custo explode.Long-lived branches per team or feature: every merge forces everyone to resync and retest. With 5 to 10 branches you can cope; with hundreds the cost explodes.

E o que escalaAnd what does scale

  • A Regra da Rotatividade (Churn Rule): quem muda a infraestrutura é quem migra os usuários, ou mantém a compatibilidade. Um grupo de especialistas faz o trabalho uma vez, bem feito, em vez de cada time fazer mal.The Churn Rule: whoever changes the infrastructure is the one who migrates the users, or keeps backward compatibility. A group of experts does the work once, and well, instead of every team doing it badly.
  • A Regra da Beyoncé: “se você gostou, devia ter posto um teste”. Se uma mudança de infraestrutura quebra seu produto mas nenhum teste do CI avisou, a culpa não é de quem mudou. Isso permite que times de infra mexam no código de todos sem perguntar um a um.The Beyoncé Rule: “if you liked it, you should have put a test on it”. If an infrastructure change breaks your product but no CI test flagged it, it is not the fault of whoever made the change. This lets infrastructure teams change everyone’s code without asking one team at a time.
  • Trabalho frequente fica barato: o Google demorou a atualizar um compilador em 2006 (foi doloroso, anos sem trocar). Para algumas linguagens, hoje atualiza a cada uma ou duas semanas. Quanto mais se faz, mais se automatiza e menos código frágil sobra.Frequent work gets cheap: Google struggled to upgrade a compiler in 2006 (it was painful after years without changing). For some languages, it now upgrades every week or two. The more you do it, the more you automate and the less fragile code remains.
Moral: parar no tempo é uma opção, mas raramente sábia. Sem atualizações você fica sem correções de segurança e sem ganhos de eficiência. O que protege é praticar a mudança até ela ficar barata.Moral: standing still is an option, but rarely a wise one. Without upgrades you lose security fixes and efficiency gains. What protects you is practicing change until it gets cheap.

Trade-offs, custos e “shift left”Trade-offs, costs and “shift left”

Decidir é pesar custos, e o livro lembra que custo não é só dinheiro:Deciding is weighing costs, and the book reminds us that cost is not only money:

  • Financeiro (dinheiro), de recursos (CPU, memória) e de pessoas (horas de engenharia);Financial (money), resource (CPU, memory) and personnel (engineering hours);
  • De transação (quanto custa agir) e de oportunidade (quanto custa não agir);Transaction (what it costs to act) and opportunity (what it costs not to act);
  • Social: em escala de bilhões de usuários, pequenas falhas de acessibilidade ou de justiça viram grandes danos.Societal: at billions of users, small accessibility or fairness gaps become big harms.

Exemplo do livro: marcadores de quadro branco. Em muitas empresas eles são raros e trancados, e metade está seca. No Google há armários abertos cheios deles. A troca é consciente: custa menos que um dólar o marcador, e atrapalhar um brainstorming custa muito mais do que alguns marcadores levados embora. Esse é o tipo de conta que o livro quer que você faça, de olhos abertos.A book example: whiteboard markers. In many companies they are scarce and locked up, and half of them are dry. At Google there are open closets full of them. The trade is deliberate: a marker costs less than a dollar, and disrupting a brainstorm costs far more than a few stolen markers. That is the kind of arithmetic the book wants you to do, eyes open.

Shift leftShift left

Imagine a vida de uma mudança numa linha do tempo: design, código, review, teste, commit, canário, produção. Achar um problema mais à esquerda custa menos. Por isso o livro insiste em testes, análise estática e code review antes do commit, em camadas (nenhuma é perfeita, então se usa defesa em profundidade).Picture a change’s life on a timeline: design, code, review, test, commit, canary, production. Finding a problem further left costs less. That is why the book insists on tests, static analysis and code review before the commit, in layers (none is perfect, so you use defense in depth).

DesignCódigoCodeReviewTesteTestCommitCanárioCanaryProduçãoProductionachar o problema aqui sai baratofinding the problem here is cheapA altura da barra é o custo de consertar. Quanto mais à esquerda você pega o erro, menos ele custa.The bar height is the cost of fixing. The further left you catch a bug, the less it costs.
“Shift left”: levar a detecção de problemas para o começo da linha do tempo.“Shift left”: moving problem detection to the start of the timeline.

Equipes e culturaTeams and culture

A segunda parte do livro vale ouro e quase não tem código. A tese: engenharia de software é um esforço de equipe, e o mito do “gênio solitário” atrapalha.The book’s second part is gold and has almost no code. The thesis: software engineering is a team effort, and the “lone genius” myth gets in the way.

  • Não se esconda. Trabalhar sozinho por semanas e só mostrar o resultado pronto é arriscado: você pode gastar tudo na coisa errada. Mostrar cedo traz feedback cedo.Don’t hide. Working alone for weeks and showing only the finished result is risky: you may spend it all on the wrong thing. Showing early brings feedback early.
  • Fator ônibus (bus factor): quantas pessoas precisam “ser atropeladas por um ônibus” para o projeto parar? Compartilhar conhecimento aumenta esse número.Bus factor: how many people would have to be “hit by a bus” for the project to stall? Sharing knowledge raises that number.
  • Humildade, respeito e confiança: os três pilares da interação social. Você não é o centro do universo, trata os colegas como pessoas e confia que eles sabem o que fazem.Humility, respect and trust: the three pillars of social interaction. You are not the center of the universe, you treat colleagues as people and you trust they know what they are doing.
  • Post-mortem sem culpados: depois de um incidente, o foco é entender o que falhou no sistema, não quem errou. Assim as pessoas contam a verdade.Blameless post-mortems: after an incident the focus is what failed in the system, not who erred. That way people tell the truth.
  • Segurança psicológica e compartilhar conhecimento: perguntar deve ser seguro. Documentar, dar palestras e ter um lugar canônico de informação fazem o conhecimento escalar.Psychological safety and knowledge sharing: asking must be safe. Writing docs, giving talks and having a canonical source of information make knowledge scale.

Para quem lidera, o livro resume em três verbos: sempre decidir (achar o melhor trade-off do momento e iterar), sempre sair (montar um time que resolve sozinho, sem depender de você) e sempre escalar (proteger seu tempo e energia à medida que o sucesso traz mais trabalho). E, para medir produtividade, use primeiro a pergunta: “se eu medir isto, vou conseguir agir sobre o resultado?”For leaders, the book boils it down to three verbs: always be deciding (find the best trade-off of the moment and iterate), always be leaving (build a team that solves things without you) and always be scaling (protect your time and energy as success brings more work). And to measure productivity, first ask: “if I measure this, will I be able to act on the result?”

Code reviewCode review

No Google toda mudança é revisada por alguém que não é o autor antes de entrar. O livro mostra que revisar serve para mais do que achar bugs: garante que o código seja compreensível, consistente e que o conhecimento circule.At Google every change is reviewed by someone other than the author before it lands. The book shows review is for more than finding bugs: it keeps code understandable and consistent, and makes knowledge flow.

AutorAuthor 1. Colega: LGTM1. Peer: LGTM 2. Dono da pasta2. Folder owner 3. “Readability”3. Readability Pode entrarCan merge uma pessoa pode ter os 3 papéisone person can hold all 3 roles
Três tipos de aprovação, mas muitas vezes uma só pessoa cumpre os três papéis, o que mantém o processo rápido.Three kinds of approval, but often a single person fills all three roles, which keeps the process fast.

As três aprovações: um colega confere se está correto e compreensível (o famoso LGTM, “looks good to me”); o dono da pasta confere se aquilo pertence ali; e alguém com readability naquela linguagem confere o estilo e as boas práticas. Se o autor já é dono e tem readability, só precisa do LGTM do colega.The three approvals: a peer checks it is correct and understandable (the famous LGTM, “looks good to me”); the folder owner checks it belongs there; and someone with readability in that language checks style and best practices. If the author is already an owner with readability, only the peer’s LGTM is needed.

Boas práticasBest practices

  • Mudanças pequenas: cerca de 200 linhas. São revisadas mais rápido, o bug é mais fácil de localizar e o autor não fica parado esperando.Small changes: around 200 lines. They get reviewed faster, a bug is easier to pinpoint and the author is not stuck waiting.
  • Primeira resposta em cerca de um dia. Isso não significa terminar em um dia, mas dar um retorno.First feedback within about a day. That does not mean finishing in a day, just answering.
  • Descrição que explica o porquê. A primeira linha vira o título em ferramentas e no histórico; “Bug fix” não ajuda ninguém. A descrição é o registro histórico daquela mudança.A description that explains why. The first line becomes the title in tools and history; “Bug fix” helps nobody. The description is the historical record of that change.
  • Poucos revisores e muita automação: o que a máquina checa (formato, estilo, testes) não precisa gastar a atenção humana.Few reviewers and plenty of automation: what a machine can check (format, style, tests) should not use up human attention.
  • Seja educado e profissional. A revisão é também mentoria.Be polite and professional. Review is also mentoring.

TestesTesting

O livro conta a história do Google Web Server (GWS), que serve a busca. Em 2005 o projeto tinha ficado travado: mais de 80% dos deploys continham bugs que afetavam usuários e precisavam de rollback. O tech lead instituiu testes automatizados obrigatórios para toda mudança. Em um ano, os deploys de emergência caíram pela metade, mesmo com um número recorde de mudanças. Hoje o GWS tem dezenas de milhares de testes e entrega quase todo dia.The book tells the story of the Google Web Server (GWS), which serves Search. In 2005 the project had stalled: over 80% of pushes contained user-affecting bugs and had to be rolled back. The tech lead mandated automated tests for every change. Within a year, emergency pushes dropped by half, even with a record number of changes. Today GWS has tens of thousands of tests and ships almost daily.

A conta que justifica isso: um time de 100 engenheiros tão bons que cada um erra uma vez por mês ainda produz cerca de 5 bugs novos por dia útil. Só automação segura isso.The math behind it: a team of 100 engineers so good that each makes a single bug a month still produces about 5 new bugs every work day. Only automation holds that back.

Tamanho e escopoSize and scope

Para o Google, todo teste tem duas dimensões diferentes:At Google, every test has two different dimensions:

  • Tamanho é o que o teste consome e pode fazer. Pequeno: um único processo, sem rede, sem disco, sem dormir. Médio: uma máquina (pode subir um banco local). Grande: pode usar várias máquinas.Size is what a test consumes and is allowed to do. Small: a single process, no network, no disk, no sleeping. Medium: one machine (it may start a local database). Large: may span several machines.
  • Escopo é quanto código o teste verifica: estreito (unidade), médio (integração) ou amplo (ponta a ponta).Scope is how much code the test verifies: narrow (unit), medium (integration) or broad (end to end).

Os testes pequenos são rápidos e determinísticos (dão sempre o mesmo resultado). Os grandes são mais lentos e podem ser instáveis. Daí vem a pirâmide: muitos testes estreitos e rápidos na base, poucos de ponta a ponta no topo. O livro avisa para fugir do “sorvete de casquinha” (muitos ponta a ponta, poucos de unidade) e da “ampulheta”.Small tests are fast and deterministic (always the same result). Large ones are slower and can be unreliable. Hence the pyramid: many narrow, fast tests at the base, few end-to-end ones at the top. The book warns against the “ice cream cone” (many end to end, few unit) and the “hourglass”.

5% 15% 80% Ponta a ponta: o sistema todoEnd to end: the whole system Integração: poucas peças juntasIntegration: a few parts together Unidade: uma peça só, rápidaUnit: a single piece, fast grande: roda onde quiserlarge: runs anywhere média: uma máquinamedium: one machine pequena: um processosmall: one process
A mistura aproximada que o Google busca (por número de testes). Cada time ajusta a sua.The rough mix Google aims for (by number of tests). Each team tunes its own.

Testes instáveis (flaky) custam caroFlaky tests are expensive

Um teste instável às vezes falha sem motivo. Se cada teste tem só 0,1% de chance de falhar à toa e você roda 10.000 por dia, serão 10 investigações inúteis por dia. Pior que o tempo perdido é a perda de confiança: perto de 1% de instabilidade, as pessoas passam a ignorar as falhas e a suíte perde o valor. O Google mantém a taxa em torno de 0,15%.A flaky test sometimes fails for no reason. If each test has just a 0.1% chance of failing wrongly and you run 10,000 a day, that is 10 pointless investigations a day. Worse than the lost time is the lost trust: near 1% flakiness, people start ignoring failures and the suite loses its value. Google keeps the rate around 0.15%.

Testes legíveis: DAMP em vez de DRYReadable tests: DAMP over DRY

No código normal, “não se repita” (DRY) é bom. No teste, esconder tudo em funções auxiliares obriga o leitor a pular pelo arquivo para entender o que está sendo verificado. O livro prefere DAMP: “Descriptive And Meaningful Phrases”. Um pouco de repetição é aceitável se deixa o teste óbvio ao ler.In normal code “don’t repeat yourself” (DRY) is good. In a test, hiding everything in helper functions forces the reader to jump around the file to see what is being verified. The book prefers DAMP: “Descriptive And Meaningful Phrases”. A bit of repetition is fine if it makes the test obvious on reading.

@Test
public void shouldNotRegisterBannedUsers() {
  User user = newUser().setState(State.BANNED).build();
  Forum forum = new Forum();
  try {
    forum.register(user);
  } catch (BannedUserException ignored) {}
  assertThat(forum.hasRegisteredUser(user)).isFalse();
}

Outras regras do capítulo de testes unitários: testar pela API pública, testar comportamentos e não métodos, verificar o estado e não as interações, não pôr lógica (if, loops) dentro do teste, e escrever mensagens de falha claras.Other rules from the unit-testing chapter: test through the public API, test behaviors and not methods, verify state and not interactions, put no logic (if, loops) inside a test, and write clear failure messages.

Dublês de teste: prefira o realTest doubles: prefer the real thing

  • 1º: use a implementação real sempre que for viável;1st: use the real implementation whenever it is feasible;
  • 2º: se não der, um fake (uma versão simples e correta, como um banco em memória) é o ideal;2nd: if not, a fake (a simple, correct version, like an in-memory database) is ideal;
  • Evite abusar de stubs e de testes de interação (“esta função foi chamada 2 vezes”): eles amarram o teste à implementação e quebram à toa.Avoid overusing stubs and interaction tests (“this function was called twice”): they tie the test to the implementation and break for no reason.

Além disso, o livro lembra de testar falhas: simular exceções, injetar latência e erros de rede. Cobertura de código (% de linhas executadas) ajuda a achar o que ficou sem teste, mas não prova que o teste verifica algo.The book also reminds us to test failures: simulate exceptions, inject latency and network errors. Code coverage (% of lines executed) helps find what has no test, but does not prove the test verifies anything.

Ferramentas e entregaTools and delivery

A parte final trata de como a mudança chega à produção sem dor.The final part covers how a change reaches production without pain.

  • Um repositório, uma versão. Controle de versão para tudo que seja maior que um brinquedo. A “regra de uma versão” elimina a pergunta “de qual versão eu dependo?”, que não escala. Desenvolvimento no tronco (trunk-based) é, segundo as pesquisas citadas (DORA), um preditor de organizações de alto desempenho; branches longas não são um bom padrão.One repository, one version. Version control for anything bigger than a toy. The “one-version rule” removes the question “which version do I depend on?”, which does not scale. Trunk-based development is, per the research cited (DORA), a predictor of high-performing organizations; long-lived branches are not a good default.
  • Build como artefatos. Sistemas de build organizados em torno de artefatos (não de tarefas) escalam e são mais confiáveis. Prefira módulos pequenos (aproveitam paralelismo e builds incrementais) e dependências externas com versão explícita, nunca “latest”.Build around artifacts. Build systems organized around artifacts (not tasks) scale better and are more reliable. Prefer fine-grained modules (they exploit parallelism and incremental builds) and externally versioned dependencies, never “latest”.
  • Análise estática no fluxo normal. Ferramentas que apontam padrões de bug devem aparecer no code review, com correção sugerida, e ter poucos falsos positivos; senão as pessoas as ignoram.Static analysis in the normal flow. Tools that flag bug patterns should show up in code review with a suggested fix and few false positives; otherwise people ignore them.
  • Dependências são contratos. Adicionar uma dependência não é de graça: há um custo contínuo de confiança e manutenção. O versionamento semântico (SemVer) é só uma estimativa de risco, não uma garantia.Dependencies are contracts. Adding a dependency is not free: there is an ongoing cost of trust and maintenance. Semantic versioning (SemVer) is just an estimate of risk, not a guarantee.
  • Mudanças em larga escala (LSC). Com um processo próprio, dá para mudar milhares de arquivos de uma vez (por exemplo, renomear uma API). O refatoramento tradicional não aguenta essa escala.Large-scale changes (LSC). With a process of their own, you can change thousands of files at once (for example, rename an API). Traditional refactoring breaks at that scale.

Integração e entrega contínuasContinuous integration and delivery

O CI decide quais testes rodar e quando. Antes do commit (pré-submit) rodam testes rápidos e confiáveis; depois (pós-submit), os mais lentos. Na entrega contínua, o livro destaca: feature flags para isolar mudanças, rollout em etapas (canário) porque o mundo real é mais diverso que o ambiente de teste, medir se o recurso é usado, e a ideia de que mais rápido é mais seguro: entregas pequenas e frequentes têm menos risco cada.CI decides which tests to run and when. Before the commit (presubmit) quick, reliable tests run; after it (post-submit), the slower ones. For continuous delivery the book highlights: feature flags to isolate changes, staged rollouts (canary) because the real world is more diverse than a test environment, measuring whether a feature is used, and the idea that faster is safer: small, frequent releases carry less risk each.

Pré-submitPresubmitrápido, estávelfast, reliable Commit Pós-submitPost-submitlento, completoslow, thorough CanárioCanarypoucos usuáriosa few users TodosEveryoneaos poucosgradually Feature flags: o código chega à produção desligado e é ligado de forma controladaFeature flags: code reaches production switched off and is turned on in a controlled way Entregas pequenas e frequentes: quanto menor a mudança, menor o risco de cada uma.Small, frequent releases: the smaller the change, the lower the risk of each.
O caminho de uma mudança até os usuários: testes rápidos antes, testes pesados depois, e liberação gradual.A change’s path to users: quick tests before, heavy tests after, and a gradual rollout.

Como aplicar no seu projetoApplying it to your project

Você não precisa ser o Google para usar as ideias. Um roteiro bem pequeno, em ordem de retorno:You don’t need to be Google to use these ideas. A very small checklist, in order of return:

  1. Escreva testes pequenos e rápidos para as regras de negócio, e faça o CI rodá-los a cada push. Exija teste junto de toda correção de bug.Write small, fast tests for business rules and make CI run them on every push. Require a test with every bug fix.
  2. Revise em mudanças pequenas e descreva o porquê no commit.Review in small changes and describe the why in the commit.
  3. Prefira o tronco e branches curtas; esconda trabalho incompleto atrás de uma feature flag.Prefer trunk and short branches; hide unfinished work behind a feature flag.
  4. Fixe versões de dependências e atualize com frequência, em vez de a cada cinco anos.Pin dependency versions and upgrade often, rather than every five years.
  5. Documente decisões e escreva post-mortems sem culpados.Document decisions and write blameless post-mortems.
  6. Em cada processo repetido, pergunte: se a equipe for 10× maior, isto ainda cabe? Se não, automatize.For each repeated process ask: if the team were 10× bigger, would this still fit? If not, automate it.
Anotação pessoal: este resumo segue a ordem do livro, mas escolhe e simplifica. Os números e citações (80% de pushes ruins no GWS, 0,15% de testes instáveis, 200 linhas por mudança, 80/15/5 de testes) vêm do texto; os exemplos marcados como inventados são meus.Personal note: this summary follows the book’s order but picks and simplifies. The numbers and quotes (80% bad pushes at GWS, 0.15% flaky tests, 200 lines per change, 80/15/5 test mix) come from the text; examples marked as invented are mine.