惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V2EX - 技术
V2EX - 技术
T
Troy Hunt's Blog
The Last Watchdog
The Last Watchdog
www.infosecurity-magazine.com
www.infosecurity-magazine.com
S
Secure Thoughts
Hacker News - Newest:
Hacker News - Newest: "LLM"
WordPress大学
WordPress大学
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - 司徒正美
TaoSecurity Blog
TaoSecurity Blog
博客园 - Franky
有赞技术团队
有赞技术团队
Google Online Security Blog
Google Online Security Blog
罗磊的独立博客
L
LINUX DO - 最新话题
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
NISL@THU
NISL@THU
小众软件
小众软件
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Recent Commits to openclaw:main
Recent Commits to openclaw:main
K
Kaspersky official blog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
W
WeLiveSecurity
SecWiki News
SecWiki News
Google DeepMind News
Google DeepMind News
O
OpenAI News
V
V2EX
AI
AI
博客园_首页
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
美团技术团队
C
Cyber Attacks, Cyber Crime and Cyber Security
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Security Archives - TechRepublic
Security Archives - TechRepublic
博客园 - 三生石上(FineUI控件)
G
GRAHAM CLULEY
月光博客
月光博客
T
Threatpost
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
V
Vulnerabilities – Threatpost
Last Week in AI
Last Week in AI
爱范儿
爱范儿
C
CXSECURITY Database RSS Feed - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Cloudbric
Cloudbric
酷 壳 – CoolShell
酷 壳 – CoolShell
The Hacker News
The Hacker News
N
News | PayPal Newsroom
Know Your Adversary
Know Your Adversary

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Prisma Query Logging and PostgreSQL: Where the ORM Ends and the Database Begins
Juan Torchia · 2026-05-25 · via DEV Community

Prisma Query Logging and PostgreSQL: Where the ORM Ends and the Database Begins

I turned on query logging in Prisma, watched queries rolling into the console, and assumed I had full visibility into what was happening in the database. Spoiler: I didn't.

Prisma logs show the query the client sends and how long it took from the ORM's perspective — including serialization, network, and driver overhead. What they don't show is what PostgreSQL actually does with that query on the inside: whether it used an index, whether it did a sequential scan, whether there was a lock wait, whether the planner picked a bad plan. That stuff lives in Postgres, not in the ORM.

My thesis: Prisma query logs are a pattern-debugging tool, not a database diagnostics tool. Confusing the two leads you to look for the problem in the wrong place and make optimization decisions without real evidence.


What the Official Prisma Docs Say — and What They Don't

The official Prisma logging documentation is clear about what the system offers: three log levels (INFO, WARN, ERROR) plus the special query level, which emits the SQL query, parameters, duration, and target.

The basic setup looks like this:

// Initialize the client with query logging enabled
const prisma = new PrismaClient({
  log: [
    {
      emit: 'event',   // emit as event so we can handle it ourselves
      level: 'query',
    },
    {
      emit: 'stdout',  // errors and warnings go straight to console
      level: 'error',
    },
    {
      emit: 'stdout',
      level: 'warn',
    },
  ],
})

// Listen to the query event to log with structure
prisma.$on('query', (e) => {
  console.log({
    query: e.query,       // SQL generated by Prisma
    params: e.params,     // bound parameters
    duration: e.duration, // duration in ms from the Prisma client
    target: e.target,     // datasource name (e.g. "db")
  })
})

What the docs don't mention explicitly is that e.duration measures the time from when the Prisma client sends the query to when it gets the response back. That number includes network latency, driver parsing, result serialization, and potential connection pool contention. It is not the time PostgreSQL spent executing the query. Those are different things, and mixing them up produces bad diagnoses.

To capture real execution time in Postgres, you need pg_stat_statements or EXPLAIN ANALYZE directly on the database. Those tools live on the engine side, not the ORM side.


The Most Common Mistake: Confusing Client Duration with Postgres Execution Time

A classic pattern in teams just getting started with Prisma: they see a query with duration: 800 in the logs and conclude "this query is slow." Maybe it is. But it could also be that the query runs in 20ms inside Postgres and the remaining 780ms are pool contention, network latency, or deserialization overhead from a bloated result set.

Without separating those times, any optimization you make is speculative.

A concrete scenario where this bites you: you're querying a table with lots of columns and pulling SELECT * because Prisma, by default with findMany(), fetches every field. Execution time in Postgres might be perfectly reasonable, but transfer time and payload serialization could be what's inflating the duration you see in the log. The fix isn't an index — it's an explicit select:

// Instead of fetching all fields (default findMany behavior)
const users = await prisma.user.findMany()

// Select only what we actually need
const users = await prisma.user.findMany({
  select: {
    id: true,
    email: true,
    createdAt: true,
    // exclude heavy columns like avatarBase64, metadataJson, etc.
  },
})

This change can drop the duration you see in logs without touching a single index. If you'd gone straight to Postgres to "optimize the query," you would've burned time hunting a problem that wasn't there.


When Prisma Logging Is Enough and When You Need to Look at PostgreSQL

This is the technical decision that matters most. Here's a criteria guide based on what each layer can and can't show you:

Prisma query logging is enough when:

  • You're spotting an N+1: you see dozens of identical queries in the log for a single request. This is where Prisma logging genuinely shines. If you want to go deeper on N+1 patterns in Server Actions, there's more context in this post on Prisma and Next.js 16.
  • You're hunting unnecessary queries: logs show you if a screen is making queries it has no business making.
  • You're verifying an explicit select works: you can confirm Prisma generates the right SQL before it ever hits the database.
  • You're debugging badly written filters: the logged query shows you whether your where clause translates the way you expect.
  • You're mapping query frequency by endpoint: with event-based emit you can count and group without any external tooling.

You need to look at PostgreSQL directly when:

  • Client duration is high but the query pattern looks correct: dig into pg_stat_statements to see real execution time in Postgres.
  • You suspect a sequential scan: EXPLAIN ANALYZE on the same query tells you if there's an index that isn't being used.
  • There are locks or deadlocks: pg_locks and pg_stat_activity are the tools. Prisma can't see any of this.
  • The problem shows up under load but not locally: that's likely pool contention or autovacuum triggering at real volume. Neither of those shows up in ORM logs.
  • You want to understand the query planner's plan: the plan can change with real data and real table statistics. Only EXPLAIN ANALYZE shows you that.
-- Run this directly in PostgreSQL to see the real execution plan
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT u.id, u.email
FROM "User" u
WHERE u.status = 'active'
ORDER BY u."createdAt" DESC
LIMIT 50;

-- BUFFERS shows how many blocks were read from disk vs cache
-- ANALYZE actually executes the query (be careful on tables with heavy writes)


Diagnostic Checklist: Where to Start

Before optimizing anything, answer these questions in order:

1. Does the Prisma log show many queries for a single operation?
   → Yes: check for N+1, eager loading, misconfigured relation loading
   → No: keep going

2. Does the generated SQL make sense? Are we pulling columns we don't use?
   → Problem: add explicit select in Prisma
   → OK: keep going

3. Is the duration in Prisma consistently high or sporadic?
   → Sporadic: investigate pool contention, exhausted connections
   → Consistent: keep going

4. Do you have pg_stat_statements enabled in PostgreSQL?
   → No: enabling it is the next step before you continue diagnosing
   → Yes: find the query by query text and check real mean_exec_time

5. Does the execution plan use an index or a sequential scan?
   → EXPLAIN ANALYZE on the real query with real data
   → If there's a seq scan on a large table with filters, that's your problem


Hard Limits: What You Cannot Conclude from Prisma Logs Alone

This matters and not enough people say it clearly:

  • You can't conclude "the query is slow" based only on e.duration without knowing how much of that time is Postgres vs driver overhead vs network.
  • You can't detect lock waits or deadlocks from the ORM client. A query waiting on a lock will show up with a high duration, but the reason is invisible from Prisma.
  • You can't see if autovacuum is competing with your writes. That background noise shows up as intermittent slowness that doesn't correlate with any pattern in the client log.
  • You can't validate that an index is being used without EXPLAIN. Prisma generating a correct WHERE clause doesn't guarantee Postgres will pick the index you expect.
  • You can't reproduce behavior under real load with local logs alone. The pool has a max size (configurable with connection_limit in the datasource), and contention only appears with real concurrency.

If the diagnosis requires any of those points, Prisma logs are a starting point, not the answer.


FAQ: Prisma Query Logging and PostgreSQL

How do I enable query logging in Prisma without dumping everything to stdout?

Use emit: 'event' instead of emit: 'stdout' and handle it via prisma.$on('query', handler). That way you can filter, structure, or ship it to your logging system without polluting standard output in production.

Is the duration in Prisma logs the same as execution time in PostgreSQL?

No. Prisma client duration includes serialization, network latency, and driver overhead. Real execution time in Postgres comes from pg_stat_statements or EXPLAIN ANALYZE. They can differ significantly depending on result size and network latency.

How do I enable pg_stat_statements in PostgreSQL?

Add pg_stat_statements to shared_preload_libraries in postgresql.conf, restart the server, and run CREATE EXTENSION IF NOT EXISTS pg_stat_statements; on your database. From there you can query pg_stat_statements to see real execution times per query.

Does it make sense to log queries in production?

Depends on the volume. In production with high traffic, logging every query can generate significant I/O overhead. A more sensible approach is logging only queries that exceed a duration threshold, or using OpenTelemetry with sampling. I covered observability with traces in the context of Spring Boot but the principles are the same — more detail in the OpenTelemetry post.

Does Prisma have any native way to run EXPLAIN ANALYZE?

Not natively. You can use prisma.$queryRaw to run EXPLAIN ANALYZE manually:

// Run EXPLAIN ANALYZE via queryRaw to see the real execution plan
const plan = await prisma.$queryRaw`
  EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)
  SELECT id, email FROM "User" WHERE status = 'active'
`
console.log(JSON.stringify(plan, null, 2))

This is useful in development to validate that the planner is using the indexes you expect.

If I don't see slow queries in Prisma logs, can I assume the database is fine?

No. The absence of slow queries on the client side doesn't guarantee there are no problems in Postgres. There can be table bloat, stale indexes, delayed autovacuum, or queries that run fast individually but create cumulative pressure. Database diagnostics require their own tools.


My Take: These Are Different Layers, Not Alternatives

The uncomfortable thing about this topic is that most Prisma documentation — including the official docs — shows you how to configure logging without explicitly clarifying what it measures and what it doesn't. That creates a reasonable but wrong assumption: that having query logging turned on equals having visibility into database behavior.

It doesn't. Prisma logging is ORM-layer debugging. PostgreSQL has its own observability layer and needs its own tools. Both are necessary and they complement each other, but neither replaces the other.

My practical recommendation: use Prisma logging to catch query patterns — N+1, unnecessary selects, duplicate queries per request. When the pattern looks fine and the problem persists, move to pg_stat_statements and EXPLAIN ANALYZE. Don't skip the first step because it's easier to enable, but don't stay there if the answer doesn't show up.

The concrete next step: if you have pg_stat_statements disabled on your database, that's the first thing I'd enable. Without it, you're diagnosing blind in the layer that matters most.


Original sources:


This article was originally published on juanchi.dev