เหตุใดการเชื่อมต่อจึงมีต้นทุนสูงใน PostgreSQL
ทำความเข้าใจต้นทุนหน่วยความจำและการจัดตารางเวลาต่อแบ็กเอนด์ ซึ่งทำให้การใช้พูลมีความจำเป็นเมื่อระบบขยายใหญ่
เหตุใดการเชื่อมต่อจึงมีต้นทุนสูงใน PostgreSQL เป็นบทเรียน PostgreSQL Performance & Query Optimization ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน PostgreSQL Performance & Query Optimization และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส PostgreSQL Performance & Query Optimization มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
One Connection, One Process
PostgreSQL uses a process-per-connection model. Every client connection is handled by its own dedicated OS process called a backend, forked from the postmaster when the connection is accepted.
This design is robust and simple, but it has a real cost: a process is far heavier than a thread. Unlike databases that multiplex many sessions onto a thread pool, PostgreSQL pays a per-process price for every single open connection, whether it is actively running a query or sitting idle.
You can see one backend per connection directly in the catalog:
SELECT pid, usename, application_name, state
FROM pg_stat_activity
WHERE backend_type = 'client backend';The Cost of Forking
Opening a connection is not free. Each new backend requires PostgreSQL to:
- Fork a new OS process from the postmaster
- Attach to shared memory and set up its local memory context
- Authenticate the client and validate the database/role
- Load catalog and relation cache entries on first access
This setup can take several milliseconds before a single query runs. An application that opens and closes a connection for every HTTP request pays this tax thousands of times per minute, turning connection churn into a measurable latency and CPU drain.
Per-Backend Memory Is Not Shared
Beyond the shared buffer pool, every backend allocates its own private memory. The key per-connection knobs are local to each session:
work_mem— memory for each sort, hash, or grouping operationtemp_buffers— memory for temporary tables- Catalog and plan caches that grow as the session touches more objects
Critically, work_mem is allocated per operation, per connection. A single complex query with several sorts and hash joins can use multiples of work_mem at once.
SHOW work_mem;
SHOW temp_buffers;
SHOW shared_buffers;Why work_mem Multiplies
The danger with work_mem is that it is not a per-connection cap — it is a per-operation grant. A plan with three sorts and two hash joins can request work_mem five times simultaneously.
Estimate the worst case roughly as:
peak_RAM ≈ max_connections × work_mem × avg_operations_per_query
With max_connections = 500, work_mem = 16MB, and a few sorts per query, you can theoretically reach tens of gigabytes of transient memory — long before you account for shared buffers or the OS page cache.
-- Rough back-of-envelope ceiling
SELECT
current_setting('max_connections')::int AS max_conn,
current_setting('work_mem') AS work_mem,
current_setting('max_connections')::int
* (pg_size_bytes(current_setting('work_mem')) / 1024 / 1024)
AS naive_worst_case_mb;Idle Connections Still Cost You
A common misconception is that an idle connection is free. It is not. Even a backend doing nothing:
- Holds an OS process slot and its private memory caches
- Occupies a slot counted against
max_connections - Must be visited by background scans of
pg_stat_activityand snapshot logic - If
idle in transaction, it can pin old row versions and block vacuum
Hunting down long-lived idle and idle-in-transaction sessions is one of the first things to check on a struggling server:
SELECT pid, state, wait_event_type,
now() - state_change AS idle_for
FROM pg_stat_activity
WHERE state IN ('idle', 'idle in transaction')
ORDER BY idle_for DESC;Snapshots and the Visibility Tax
PostgreSQL's MVCC model means every query takes a snapshot of which transactions are visible. Building and maintaining that snapshot involves scanning the list of currently active backends.
As the number of connections grows, this bookkeeping becomes more expensive. Historically (pre-PostgreSQL 14), GetSnapshotData() scaled with the total number of connections, so thousands of mostly-idle backends added overhead to every active transaction.
The lesson: more connections do not just use more memory — they make the shared coordination work harder for everyone.
The CPU Scheduling Wall
Backends are real OS processes, so the kernel scheduler must time-slice them across your CPU cores. When runnable backends greatly outnumber cores, you hit a wall:
- More context switching burns CPU on overhead, not query work
- Cache locality drops as processes are shuffled on and off cores
- Lock contention on shared structures rises with concurrency
This is why throughput often peaks then declines as concurrency climbs past the core count. A box with 16 cores rarely benefits from 400 simultaneously active queries.
SELECT count(*) AS active_queries
FROM pg_stat_activity
WHERE state = 'active'
AND backend_type = 'client backend';Sizing max_connections Realistically
It is tempting to set max_connections very high "to be safe," but that backfires. Each potential connection reserves shared-memory bookkeeping and raises the ceiling on memory and scheduling pressure.
A practical rule of thumb for a CPU-bound workload is something like:
active_connections ≈ cores × 2 to cores × 4
You want max_connections set just high enough to cover real concurrency plus headroom — not to absorb thousands of application threads each grabbing a raw connection.
SHOW max_connections;
SELECT count(*) AS current_connections
FROM pg_stat_activity;Where the Money Goes: A Tiny Model
Here is a self-contained way to reason about the per-connection ceiling using only constants. It estimates worst-case transient query memory for a fleet of connections — no server or tables required, so you can run it anywhere.
The point is to make the multiplication visible: connections times per-operation memory times operations per query is the number that surprises people.
WITH params AS (
SELECT 400 AS max_conn,
16 AS work_mem_mb,
3 AS avg_ops_per_query,
8192 AS shared_buffers_mb
)
SELECT
max_conn,
work_mem_mb,
avg_ops_per_query,
max_conn * work_mem_mb * avg_ops_per_query AS worst_case_query_mb,
shared_buffers_mb
+ max_conn * work_mem_mb * avg_ops_per_query AS total_ceiling_mb
FROM params;The Fix: Pool, Don't Multiply
The escape from all of these costs is connection pooling. Instead of giving every application thread its own raw backend, a pooler keeps a small set of warm PostgreSQL connections and multiplexes many clients over them.
- Backends are reused, so the fork/auth/cache-warm cost is paid once, not per request
- Active backends stay near the core count, avoiding the scheduling wall
- Total private memory is bounded by the pool size, not the client count
PgBouncer is the canonical lightweight pooler for exactly this reason — it is the subject of the rest of this course.
Diagnosing Connection Pressure
Before tuning a pool, measure where you stand. A quick health snapshot groups current sessions by state so you can see how many are truly active versus idle.
If you see hundreds of idle connections and only a handful active, you are paying the full per-backend memory and scheduling tax for capacity you never use — a textbook case for pooling.
SELECT state,
count(*) AS sessions,
max(now() - state_change) AS oldest
FROM pg_stat_activity
WHERE backend_type = 'client backend'
GROUP BY state
ORDER BY sessions DESC;Quick Check
Test your understanding of per-connection costs in PostgreSQL.
Recap: Why Connections Are Expensive
Key takeaways from this lesson:
- PostgreSQL uses a process-per-connection model — every connection is a forked OS backend, not a cheap thread.
- Opening a connection pays a real fork, auth, and cache-warming cost before any query runs.
work_memandtemp_buffersare per-backend, per-operation, so memory multiplies with connections and operations per query.- Idle connections still hold slots, memory, and add snapshot overhead; idle-in-transaction can block vacuum.
- Too many active backends cause context-switch and lock contention, so throughput peaks near the core count.
- The remedy is connection pooling (PgBouncer): reuse a small set of warm backends instead of one per client.
เรียนรู้ SQL ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 22
- บทเรียน
- 88
คำถามที่พบบ่อย
บทเรียน “เหตุใดการเชื่อมต่อจึงมีต้นทุนสูงใน PostgreSQL” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “เหตุใดการเชื่อมต่อจึงมีต้นทุนสูงใน PostgreSQL” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส PostgreSQL Performance & Query Optimization ให้อัปเกรดเป็น CoddyKit PRO คอร์ส PostgreSQL Performance & Query Optimization มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “เหตุใดการเชื่อมต่อจึงมีต้นทุนสูงใน PostgreSQL”
ทำความเข้าใจต้นทุนหน่วยความจำและการจัดตารางเวลาต่อแบ็กเอนด์ ซึ่งทำให้การใช้พูลมีความจำเป็นเมื่อระบบขยายใหญ่ คุณปฏิบัติ PostgreSQL Performance & Query Optimization ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน PostgreSQL Performance & Query Optimization หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน PostgreSQL Performance & Query Optimization บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “เหตุใดการเชื่อมต่อจึงมีต้นทุนสูงใน PostgreSQL” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน PostgreSQL Performance & Query Optimization นี้ได้ไหม
ได้ บทเรียน PostgreSQL Performance & Query Optimization ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- เหตุใดการเชื่อมต่อจึงมีต้นทุนสูงใน PostgreSQL
- โหมดพูลแบบธุรกรรมเทียบกับแบบเซสชัน
- การกำหนดขนาดพูลให้สอดคล้องกับจำนวนคอร์
- การวินิจฉัยพูลเต็มและการเข้าคิว