Combinar tarefas e recompensas com os filhos é fácil. Difícil é lembrar do combinado, acompanhar o que foi feito e evitar aquelas discussões sobre quem fez o quê. Foi para resolver esse problema que criei o Star Catcher, um aplicativo que transforma boas atitudes em estrelas que a criança pode juntar para conquistar seus próprios objetivos.
No Star Catcher, os pais definem quais comportamentos valem estrelas, aprovam as missões realizadas e acompanham o progresso. A criança tem seu próprio aplicativo, sem dinheiro ou preços na tela, e consegue visualizar suas estrelas, objetivos e conquistas. É uma forma simples de tornar os combinados mais claros e motivadores para toda a família.
👉 Quer conhecer o aplicativo e ver como funciona? Acesse a página do Star Catcher e saiba mais: Conheça o Star Catcher
The evolution of APIs seems to have plateaued in recent years. While Artificial Intelligence tools and autonomous agents evolve at an absurd speed, the way our APIs deliver data remains rigid and stuck in the past.
If you work in development, you’ve probably realized: we are trying to connect machines to systems that still rely on manuals made for humans. And that’s where the problem begins.
The Bottleneck: APIs Built for Humans, Used by Agents
When we create a traditional API, we design everything expecting a human to be in control. We assume the developer on the other side will read the documentation, understand the system’s nuances, and have the common sense to respect limits to avoid breaking anything.
The problem is that LLMs (Large Language Models) lack this intuition. They are literal. If you give an endpoint to an AI agent and ask for a bulk task, it will execute it as fast and as crudely as possible, unaware that this “bombardment” of requests could crash your server due to a lack of clear guidance on expected behavior.
The Danger of Missing Context: The “Killer” Script
Imagine the following scenario: you ask an AI to read 1,000 objects from an API and clone that data to another endpoint. It’s a trivial task.
Without context: The AI generates a simple for loop and fires off 1,000 requests in milliseconds.
The result: For many systems, this is an involuntary DoS attack. The AI delivered exactly what you asked for, but the system crashed because it didn’t know it needed to “throttle down.”
The Idea: The CONTEXT method
Inspired by the OPTIONS method (which browsers already use to understand permissions), why not create a standard specifically for AI agents? The idea is to explore a concept for a method called CONTEXT.
The flow would work like this: before an agent performs any GET, POST, or DELETE, it would do a quick query to the endpoint using this “context” method.
How this changes the game in practice
When querying this metadata, the API would return a JSON with the system’s “etiquette rules.” Example:
JSON
{
"endpoint": "/v1/clone-objects",
"rules": {
"rate_limit_advice": "Never make more than 5 requests per second",
"criticality": "high",
"side_effects": "This command generates heavy load on the database"
}
}
With this information in hand, the AI changes its behavior instantly. Instead of an aggressive script, it generates code with a sleep (pause) between calls, respecting the infrastructure’s health without you having to explicitly state this in the initial prompt.
The Future is Standardizing Context
We need to stop creating external scripts and “workarounds” to try and control AIs. Ideally, APIs should provide the necessary context for agents to work safely in a standardized and natural way.
Providing context should be the standard, not the exception. Just as we check for CORS permissions, we should check an API’s “expected behavior” before any interaction.
What do you think of this approach? Do you believe a metadata standard for agents would make integrations safer, or do you prefer to control everything via prompting?
Recently, the first Cursor community Meetup took place in Rio de Janeiro, hosted by Bemobi, and I had the pleasure of attending. This content only exists thanks to the collaboration of the team and the constant encouragement from our TM to explore new approaches. I decided to turn my presentation into a blog post to share how we are using Cursor in our daily work and the strategy we are adopting.
The Software Development Life Cycle (SDLC) is the backbone of any technology project. However, for decades, we have followed its phases manually and often in a disconnected way. But what if we could infuse each stage with artificial intelligence, transforming AI from a point solution into a true strategic partner?
In this article, I will show how an “AI-Infused SDLC” approach, using the Cursor IDE, can change the way we plan, design, and build software.
The Core Tool: Cursor and Its “Rules”
Before diving into the SDLC phases, it is essential to understand the central component of this approach: the Cursor IDE. Cursor is a code editor specifically designed to work with AI. Its main strength lies in the ability to inject precise context through “Cursor Rules.”
Cursor Rules act as a structured contextual memory for the AI model.
We started with a simple setup: a single rule for the project. However, it quickly became clear that it was difficult to explicitly express what the rule was doing and how we could scale this approach across different projects. To address this, we decided to organize our rules into hierarchical layers:
– Team-wide generic rules: file standards, development best practices, and methodological approaches. – Project-specific rules: technology stack, code patterns, and internal conventions. – Organizational information: communication channels, tools in use, and established processes. – Business rules: domain-specific requirements, such as settlement rules or custom validations. – System architecture: physical and semantic organization of the project.
The result is a rich context that allows the AI to generate PRDs, implementations, and documentation fully aligned with the project—transparently for the user who is writing the prompt.
Phase 1: Planning — Intelligent Planning
Planning is the initial phase where objectives, scope, and feasibility are defined. With Cursor, this stage gains a deeper analytical dimension through intelligent information processing.
AI can consolidate data from multiple sources to support strategic decisions:
– Market analysis: processing research documents and trend reports – Technical evaluation: reviewing similar architectures and available technologies – Effort estimation: based on historical projects and identified complexity – Documentation from related projects
The outcome is a well-grounded project roadmap that serves as a solid foundation for the next phases.
Phase 2: Intelligent Requirements Analysis
Requirements analysis is traditionally one of the most critical phases of the SDLC, where clarity directly impacts project success. A key differentiator of this approach is that the IDE operator does not necessarily need to be a developer. With Cursor and well-defined contextual rules, a Product Owner can effectively lead this phase.
By using the Model Context Protocol (MCP), the AI gains authorized access to multiple knowledge sources, building a deep and multidimensional understanding of the problem.
Practical scenario led by a Product Owner:
– Code analysis: the AI scans the repository to map the current architecture, identify existing patterns, and highlight potential impact points. – Database inspection: schemas and data are analyzed to understand how a new feature will affect the existing structure. – Document review: meeting transcripts, technical specifications, and design documents are processed to extract key requirements.
The final output is a detailed task automatically created in Jira, including a technical summary, impact analysis, and preliminary acceptance criteria—all without disrupting the developers’ workflow.
Phase 3: Collaborative Design and Prototyping
With the initial task structured, we move into the Design phase. This is where we resist the temptation to “jump straight into coding” and instead focus on refining the solution. At this stage, the development team takes the lead, using AI as a brainstorming and prototyping partner.
The main objective is to create a detailed development plan, often materialized as a task list within the repository itself. This artifact acts as a critical bridge between business needs and an executable technical roadmap.
Iterative refinement of the task list with Cursor support:
– Generating code examples to illustrate proposed approaches (e.g., “For the new endpoint, we could follow this DTO pattern”) – Suggesting function structures (e.g., “The interest calculation logic can be encapsulated in a dedicated function”) – Proposing architectural patterns suitable for the project context
Important: all generated examples are added to the task list as guidance only. No production code is modified at this stage. This is a moment for strategic planning and expectation alignment.
This phase is essential because the task list breaks the delivery into smaller, manageable pieces and ensures that the plan is structured so that anyone can pick up the work at any point.
Phase 4: Strategic Coding — Controlled Scaling
With a clear technical roadmap, we move into the coding phase following a “controlled scaling” philosophy: progressing step by step, task by task, with continuous validation. This replaces chaotic execution with a safe, methodical process. It is no longer about writing a context-less prompt and expecting the AI to solve everything.
Each task is executed with full context awareness, leveraging all previously generated artifacts.
Article Scope
This article focuses on the first four phases of the SDLC: Planning, Analysis, Design, and Coding. The remaining stages—Testing, Deployment, and Maintenance—can also be significantly transformed by AI, but they will be covered in future articles.
Note that prompt engineering is not the main focus here, but those interested in going deeper can explore it separately.
Challenges and Key Considerations
Adopting AI in the SDLC is not without challenges:
– Context rot: excessive tokens can degrade model accuracy. Being selective about what context is provided is essential. – Overreliance: AI-generated code must always undergo rigorous human review. Undetected errors can cause serious production issues. AI is a powerful partner, never a flawless replacement. – Redundant documentation: AI may generate excessive or disorganized documentation. Curation processes are required to keep content relevant and up to date.
The core mantra: be patient and meticulous. Every output must be reviewed with technical rigor.
Lessons Learned
Even in an experimental phase, several insights have already emerged:
– Developer leveling: less experienced engineers gain confidence by using AI as an always-available senior pair programmer. – Acceleration for seniors: senior developers significantly speed up repetitive tasks, freeing time for architectural challenges and strategic decisions. However, due to initial distrust, they often validate context independently before fully embracing AI suggestions. – Input quality is critical: all provided context matters. Team discussions, architectural decisions, and business rules must be carefully documented and accessible to maximize AI effectiveness.
Conclusion: Toward an Intelligent SDLC
An AI-infused SDLC, especially when supported by tools like Cursor IDE, represents a natural evolution of software development. It is not about replacing human expertise, but about exponentially amplifying it.
What has been your experience with AI in software development? Share in the comments how you have been using tools like Cursor in your projects.
Every now and then, I find myself discussing software architecture with peers. While I’ve jotted down some ideas here and there, I’ve always felt there was one perspective missing—a view that goes beyond the buzzwords of clean architecture, ports and adapters, and DDD. Or maybe, on second thought, it fits right between these approaches, as they all draw from similar principles.
Ultimately, this may not be groundbreaking. But perhaps it’s something that your “zero to hero” course didn’t cover. So, I decided to leave another piece of the puzzle here—this ever-evolving enigma we call software architecture.
Domain
In the context of Domain-Driven Design (DDD), the domain is, essentially, the core of the system. It’s the area of focus or the problem the software was created to solve. Think of the domain as the part of the real world that the software models and interacts with.
It sounds simple, right? And it’s a concept you’ll encounter in many books and articles. But in practice, applying this idea is far from… linear.
Between Books and Real-World Chaos
One of the most iconic images of DDD is a clean separation of subdomains, each managed by distinct teams and systems. For example:
Team A: Responsible for Optimal Acquisition, Purchasing, Inventory, and Resource Planning.
In an ideal world, everything would be neatly organized, running like clockwork, with perfect synergy between teams and subdomains.
But let’s add a pinch of reality. Imagine that, in the second week of the project, the company realizes Team A is overwhelmed. They restructure:
Team B: Takes over Purchasing.
Team C: Handles Resource Planning.
Weeks later, someone from Team C leaves, forcing them to merge with Team B, creating Team BC. To complicate things further, Team A transfers part of Inventory management to Team BC.
Now, the question is: Could your systems handle these team changes without breaking down? Does the way you build software allow you to reorganize components quickly and efficiently?
What I See Around Me
While the classic “models”, “views”, and “controllers” folder structure is becoming outdated, many projects still follow similar patterns—just with different folder names. For example, a single “infrastructure” folder crammed with everything.
Even though popular literature on DDD and clean architecture isn’t prescriptive about folder organization, I still see developers attempting to replicate these structures blindly, without considering whether they make sense for their project.
The System Isn’t Yours Alone (or Even Your Team’s)
Change is inevitable. Keeping this in mind, I prefer building systems based on modules—cohesive units with low coupling, designed to be easy to move or even delete if needed.
To achieve this, it’s crucial to understand that much of the infrastructure code must align with the domain’s needs. This close relationship makes it logical to treat infrastructure and domain as a unified logical unit.
But beyond infrastructure and domain, there’s another crucial component in my system design: libraries (or libs, cross cuttinglibs).
The Role of Libs
Libs are standalone components—they don’t depend on the domain. This makes them reusable across projects, enhancing modularity and sustainability in the long run.
Here’s a basic representation of the structure:
However, unlike infrastructure, libs don’t submit to the domain. They’re fully independent, allowing reuse in any project:
In larger systems with multiple modules, the structure evolves further:
The Golden Rule: No Direct Sharing
Nothing is shared directly between modules—only through the lib layer (or by messaging). This ensures the system remains modular and avoids the complexity of tangled dependencies.
Why This Approach?
This structure ensures:
Flexibility: Components can be easily moved or repurposed.
Reusability: Libs can be used in multiple projects, saving effort.
Isolation: Problems in one module won’t directly affect others.
This mindset helps build systems that adapt to organizational changes while avoiding technical debt snowballs.
Conclusion
I didn’t share much code here, but I tried to convey how the approaches we choose for structuring systems are more than just technical decisions—they shape, and are shaped by, our day-to-day work.
Every design decision, from module organization to lib reuse, influences the challenges and opportunities we face in a project. Viewing architecture as a living entity that evolves with your team and business needs is the key to building sustainable, adaptable systems.
I hope this reflection encourages you to evaluate your architectural choices with a practical and strategic mindset. After all, software architecture is less about diagrams and more about creating a foundation that supports growth without chaos. 🚀
Sempre tive alguns cadernos de ideias que nunca saíram do papel , agora, já sem os cadernos, resolvi criar uma pagina aqui pra ir retroalimentando com essas ideias. Aqui deixarei somente os gatilhos, mas que provavelmente existe um doc mais elaborado para a ideia. Quem sabe um dia, um dia…não me animo a tirar do papel.
[ libs ]
[ 2023-11 ] [ golang ] Lib capaz de mover CSV para banco de dados garantindo a integridade dos dados
[ tools ]
[ 2021-01 ] Ferramenta para permitir teste sintético complexo por meio de uma interface
[ 2022-01 ] Ferramenta para padronização do postmortem
[ games ]
[ 2021-01 ] jogo que simula a gestão de um parque de sistemas na nuvem com o foco em engenharia de confiabilidade
[ 2016-01 ] Jogo de plataforma focado em divulgar e ensinar Libras
[ 2015-01 ] Jogo para testar os conhecimentos trabalhados nas escolas com perguntas simples e de resposta rápida.
[ 2015-01 ] Battle royale de nave visão lateral, onde o objetivo é pegar a coroa e tentar ficar o maior tempo possível em sua posse
[ 2018-01 ] Jogo online de time para “guerra na corda”
[ 2018-01 ] Jogo baseado em pokémon para ensinar o matemática e português
[ wearable ]
[ 2010-01 ] Gadget para dar mais autonomia para portadores de deficiência visual em ambientes com pouca rede disponível, como no metro.
[2018-01] Gadget focado em identificar padrões simples, como número do ônibus.
Alertar é o que nos notifica quando um problema surge ou está prestes a surgir, para que a ação possa ser tomada.
Criar alertas oportunos e significativos não são fáceis, mas são necessários, já que as pessoas tendem a ignorar os alertas quando sentem que não são precisos .
Alertas são problemas
Primeiro, alertas que requerem a atenção de um humano, muitas vezes conhecido como Pages, ou também aqueles alertas que vão acordar alguem de madrugada ou tirar a atenção de alguem durante o dia devem ser urgentes, importantes, passiveis de ação e reais. O problema de ter o over-monitoring ou mais alertas do que podemos controlar significa que que os analistas responsaveis vão parar de dar atenção para os alertas, ignorar eles quando acontecerem.
Um resumo é que um alerta tem que representar um PROBLEMA, e esse problema deve ter uma ação relacionada a ele. As ações podem ser conduzir uma investigação, alguma ação como remover um servidor defeituoso do balanceamento, criar uma ação de bugfix, ou até mesmo disparar uma ação de capacity planning.
Alertas bem elaborados
Precisão :
Basicamente é a taxa de verdadeiro positivo
100% de precisão significa que cada alerta corresponde a um evento significativo.
Recall :
100% de recall significa que todo evento significativo gerou um alerta.Ou seja, com isso não temos eventos significativos acontecendo que não estamos alarmando.
Ele é a proporção de eventos significativos que são detectados e transformados em alertas.
Tempo de detecção :
Quanto tempo leva para uma condição ser detectada e transformada em alertas
Tempo de reinicialização :
Quanto tempo leva para que os alertas parem de disparar depois que a condição raiz for resolvida.
Alertas baseados em sintomas
Seus usuários se importam se seus servidores MySQL está com alto consumo de CPU? Não, eles se importam se suas consultas estão demorando
Seus usuários se importam se um binário de suporte (ou seja, caminho sem serviço) está em um loop de reinicialização? Não, eles se importam se seus recursos estão falhando.
Os usuários, em geral, se preocupam com um pequeno número de coisas:
Disponibilidade e correção básicas. sem “Oops!”, sem 500s, sem solicitações travadas ou páginas carregadas pela metade ou Javascript ou CSS ausentes ou imagens ou vídeos. Qualquer coisa que interrompa o serviço principal de alguma forma deve ser considerada indisponibilidade.
Latência. Rápido, mas somente o suficiente.
Completude/frescura/durabilidade. Os dados de seus usuários devem estar seguros, devem retornar quando você solicitar e os índices de pesquisa devem estar atualizados. Mesmo que esteja temporariamente indisponível, os usuários devem ter total fé de que ele voltará.
Features. Seus usuários se preocupam que todos os recursos do serviço funcionem – você deve monitorar qualquer coisa que seja um aspecto importante do seu serviço, mesmo que não seja a funcionalidade/disponibilidade principal
Runbooks
Importante que os alertas tenham playbooks ou runbooks, com informações sobre o que fazer, diagramas, informações sobre logs, dashboards etc. Devemos desenvolver sistemas como se quando eles derem problema seremos acordados a noite, e para evitar o esforço cognitivo de quem esta acabando de acordar eles devem conter bons runbooks, com os problemas conhecidos e melhores praticas de throbleshotting.
Rastreaveis
Os alertas precisam ser rastreáveis. Precisamos conseguir chegar facilmente na fonte do alerta.
No contexto tecnológico atual, a implementação de alertas multiwindow e multi-burn-rate representa uma abordagem inovadora para o monitoramento eficiente de sistemas. A capacidade de visualizar simultaneamente várias interfaces, combinada com alertas sensíveis a diferentes intensidades operacionais, oferece uma visão abrangente e em tempo real das operações críticas. Essa integração não apenas melhora a capacidade de resposta a eventos urgentes, mas também permite uma alocação eficiente de recursos, destacando-se como uma solução valiosa para ambientes empresariais que demandam agilidade e adaptabilidade na gestão de sistemas complexos.
Os alarmes podem ter sua criticidade mais elevada (P1) ou podem ser apenas avisos de algo que não anda bem (P4)
Janela longa e Janela curta
AS janelas de queima múltipla servem para notificar apenas quando ainda estivermos queimando ativamente o orçamento
Uma boa diretriz é fazer com que a janela curta tenha 1/12 da duração da janela longa.
Duração
Um tempo arbitrário, que normalmente é a metade da janela curta, pra evitar que um alarme fique sendo acionado com frequência. Um tempo arbitrário, que normalmente é a metade da janela curta, pra evitar que um alarme fique sendo acionado com frequência.
Taxa de queima
formula: burn rate = budget consumed x period / alert window Exemplo: budget consumed = 2% period = 30 dias = 30*24 = 720 alert window = 1h (janela de longa duração) burn rate = 0.02 * 720 / 1 = 14.4
A taxa de erro média é exatamente o fator 1, a taxa de erro que você poderia sustentar sem estourar seu orçamento de erro
Com o orçamento de erro de 0,1% (SLO 99.9%), se sua taxa de queima for 14,4% em média ao longo de uma hora (janela lonja), você obtém um alerta P1, e no momento em que a obtém , você queimou 2% do seu orçamento mensal de erros, em apenas uma hora! Isso é muito rápido. É aqui que alguém tem que acordar e consertar.
Orçamento consumido
Orçamento consumido na janela prevista. De acordo com a tabela, em 3d com taxa de queima 1 iremos consumir 10% do orçamento
A principal característica de um sistema deve ser a confiabilidade. O foco do SRE está na confiabilidade do sistema. O papel do SRE, de uma forma bem alto nível são somente dois: Medir e Garantir. E para isso existe uma série de princípios que devem ser compreendidos. Além de auxiliar no ciclo de vida do produto.
Principios para SRE
Aceitando os riscos
SLx
Eliminando Toil
Monitoração
Automação
Engenharia de Release
Simplicidade
Design de Sistema (Grandes) Não Abstrato (NALSD)
Aceitando os riscos
Aceitar o risco significa estabelecer um nível aceitável de confiabilidade, que pese os custos do que está sendo assumido em relação ao risco. E para aceitar o risco a filosofia de usar error budget precisa estar bem establecida para que funcione.
Níveis de serviço
Coração da engenharia de confiabilidade, os SLO`s, SLI`s e SLA`s e Error Budgets. o SLA, a promessa feita para o cliente, é o mínimo disposto em contrato, os SLO`s são os objetivos que você quer atingir além desse contrato, e os SLI são os indicadores que você vai utilizar pra acompanhar como estão o andamento desses objetivos.
Eliminando Toil
Reduzir as tarefas repetitivas para gastar energia em coisas urgentes com automação e um meta importante para o SRE. Simplesmente se estamos querendo reduzir nosso TOIL precisamos automatizar coisas, mas com o devido planejamento porque algo automatizado erradamente gera ainda mais pŕobelamas. O objetivo de qualificar algo como TOIL justamente indica para onde o esforço com automação deve ir, ou seja, problemas no fluxo de valor não devem ser, a priori, qualificados como TOIL.
Monitoração
Como dito anteriormente, medir e garantir. Todas as decisões tomadas devem estar pautadas em números, ou seja, certifique-se de que seu serviço produz as métricas de que você precisa. Alguns padores como 4 golden signals, RED E LEV podem fornecer o template inicial para algumas métricas.
Automação
Automatize tudo que possa ser automatizado, mas certifique-se de garantir, como qualquer outro código, a qualidade/confiabilidade por meio de testes.
Engenharia de Release
Tenha padrões de lançamento. Monitore as estatísticas sobre seus lançamentos. Entenda bem como continuous integration (CI), continuous delivery(CD) e continuous deployment (CD) funcionam de verdade.
Simplicidade
Sistemas simples tendem a ser confiáveis e fáceis de operar, porem, medir a complexidade dos sistemas não será uma tarefa fácil. Saber com quanto tempo alguém leva para fazer mudanças, ou o tempo que alguém leva pra ter uma visão abrangente de alto nível do serviço pode ajudar.
Design de Sistema (Grandes) Não Abstrato (NALSD)
Com responsabilidades que abrangem as operações de produção e engenharia de produto, a SRE está em uma posição única para alinhar os requisitos do business case e os custos operacionais. As equipes de engenharia de produto podem não estar cientes do custo de manutenção dos sistemas que projetam. Pratique a capacidade de aferir, projetar e avaliar (grandes) sistemas, não deixe nada “abstrato” antes de implementar algo. Deixar de construir um plano de falha para alguma ponta solta pode custar caro, isso não significa implementar, mas sim que evite ser pego de surpresa se algo falhar. Na fase de concepção use perguntas como:
É possível?
Isso é viável?
É resiliente?
Podemos fazer melhor?
Desta forma estaremos mais perto de construir sistemas saudáveis e duradouros.
Este vai ser um post rápido! 😉 Estou em uma jornada de confiabilidade (SRE) e aprendendo muito. Uma dificuldade inicial tem sido a evangelização das práticas, e, principalmente, a definição de SLO. Pensando nisso, e muito inspirado no VALET da The Home Depot’s, estamos indo em direção ao LEV (Latency, Errors e Volume), onde temos algumas perguntas para ajudar os devs/produto a construir os seus SLO, segue alguns exemplos:
Latency
O serviço responde rapidamente quando eu o uso?
Quão rápido meu serviço tem que ser?
O que faremos se o serviço estiver demorando mais que o esperado?
Errors
O serviço gera um erro quando eu o uso?
O que faremos se o serviço estiver com mais erro que o esperado?
Volume (traffic)
Quanto volume de negócios meu serviço pode suportar?
O que faremos se o volume for maior (ou muito menor) que o esperado?
[ update 2023-11 ]
O termo “Let Go” tem parecido mais promissor, já que, para ir para produção (Go) tem que ter o Let (Latency-Errors-Traffic) definido.
SELECT pid, now() – pg_stat_activity.query_start AS duration, query FROM pg_stat_activity WHERE state <> ‘idle’ AND pid<>pg_backend_pid() ORDER BY duration desc ;
Query travada
select pid, usename, pg_blocking_pids(pid) as blocked_by, query as blocked_query from pg_stat_activity where cardinality(pg_blocking_pids(pid)) > 0 ;
SELECT relname, CASE WHEN (seq_scan + idx_scan) != 0 THEN 100.0 * idx_scan / (seq_scan + idx_scan) ELSE 0 END AS percent_of_times_index_used, n_live_tup AS rows_in_table FROM pg_stat_user_tables ORDER BY n_live_tup DESC;
Índice corrompido
select c.relname , i.relname , x.indisvalid FROM pg_class c JOIN pg_index x ON c.oid = x.indrelid JOIN pg_class i ON i.oid = x.indexrelid where x.indisvalid = false;
Densidade da árvore de índice
SELECT avg_leaf_density FROM pgstatindex('INDEX_NAME');
SELECT attname, inherited, n_distinct, array_to_string(most_common_vals, E’, ‘) as most_common_vals FROM pg_stats;
Densidade com seletividade
WITH seletividade AS ( SELECT ‘retry’ campo,COUNT(DISTINCT retry)::NUMERIC(10,4)/COUNT(retry) AS seletividade from ordernotification ordernotif0_ UNION all SELECT ‘type’ campo,COUNT(DISTINCT type)::NUMERIC(10,4)/COUNT(type) AS seletividade from ordernotification ordernotif0_ ) , densidade AS ( SELECT ‘retry’ campo, 1.00 / ( COUNT(DISTINCT retry)::NUMERIC(10,4)/COUNT(retry) ) AS densidade FROM ordernotification ordernotif0_ UNION ALL SELECT ‘type’ campo, 1.00 / ( COUNT(DISTINCT type)::NUMERIC(10,4)/COUNT(type) ) AS densidade FROM ordernotification ordernotif0_ ) SELECT s.campo, s.seletividade, d.densidade FROM seletividade s JOIN densidade d ON d.campo::text = s.campo::TEXT — maior seletividade — menor densidade ;
Volume
Tamanho de todos os bancos
SELECT d.datname as Name, pg_catalog.pg_get_userbyid(d.datdba) as Owner, CASE WHEN pg_catalog.has_database_privilege(d.datname, ‘CONNECT’) THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname)) ELSE ‘No Access’ END as Size FROM pg_catalog.pg_database d order by CASE WHEN pg_catalog.has_database_privilege(d.datname, ‘CONNECT’) THEN pg_catalog.pg_database_size(d.datname) ELSE NULL END desc — nulls first LIMIT 20;
Tamanho das tabelas
SELECT table_name, pg_size_pretty(total_bytes) AS total , pg_size_pretty(index_bytes) AS index , pg_size_pretty(table_bytes) AS table FROM ( SELECT *, total_bytes-index_bytes-coalesce(toast_bytes,0) AS table_bytes FROM ( SELECT c.oid,nspname AS table_schema, relname AS table_name , c.reltuples AS row_estimate , pg_total_relation_size(c.oid) AS total_bytes , pg_indexes_size(c.oid) AS index_bytes , pg_total_relation_size(reltoastrelid) AS toast_bytes FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace WHERE relkind = ‘r’ ) a ) a ORDER BY total_bytes desc ;