0Pricing
System Design Basics for Backend Developers · Lekcja

Pula połączeń z bazą danych

Dowiedz się, jak pule połączeń eliminują koszt otwierania połączenia z bazą danych dla każdego żądania oraz jak dobrać i dostroić pulę pod kątem wydajności.

Pula połączeń z bazą danych to bezpłatna lekcja System Design Basics for Backend Developers na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej System Design Basics for Backend Developers, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs System Design Basics for Backend Developers zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

The Cost of a Connection

Opening a database connection is expensive: a TCP handshake, authentication, and session setup can take tens of milliseconds. Doing this on every request adds latency and load you do not need.

What a Connection Pool Is

A connection pool keeps a set of open connections ready to reuse. A request borrows one, runs its query, and returns it — no setup cost per request.

  • Lower latency
  • Less load on the database
  • A natural cap on concurrent connections

Borrow and Return

The lifecycle is simple: acquire a connection, use it, release it back to the pool. The critical rule is to always release, even on error, or the pool leaks.

conn = pool.acquire()
try:
    conn.execute('SELECT 1')
finally:
    pool.release(conn)

Pool Size Basics

The key tuning knob is the maximum pool size. Too small and requests queue waiting for a connection; too large and you overwhelm the database with concurrent work and context switching.

Sizing the Pool

Bigger is not better. A common starting heuristic is based on CPU cores, not request count, because the database can only do so much in parallel.

cores = 4
# A popular rule of thumb (HikariCP):
pool_size = (cores * 2) + 1
print('suggested pool size:', pool_size)

Queueing and Timeouts

When all connections are busy, new borrowers wait. Set an acquisition timeout so a request fails fast instead of hanging forever when the pool is exhausted. Surfacing the error early is better than a silent stall.

Connection Leaks

A leak happens when a borrowed connection is never returned. The pool slowly drains until every request blocks. Always release in a finally block (or use a context manager / try-with-resources) and enable leak detection in production.

with pool.acquire() as conn:
    conn.execute('SELECT 1')
# released automatically on exit

Idle and Max Lifetime

Tune connection longevity: an idle timeout closes connections the pool no longer needs, and a max lifetime recycles old connections to dodge stale sockets and server-side timeouts (e.g. a firewall dropping idle TCP).

Pools and Horizontal Scaling

Watch the math: 20 app servers each with a 50-connection pool means up to 1000 connections hitting one database — likely over its limit. Size per-instance pools with the total fleet in mind, or add a connection proxy.

instances = 20
per_instance = 50
print('total connections:', instances * per_instance)

External Poolers

Tools like PgBouncer sit between apps and the database, multiplexing many client connections onto a few database connections. They are essential when you have many app instances or serverless functions that each open connections.

Tuning by Measurement

Do not guess. Monitor pool metrics — active connections, wait time, timeouts — under realistic load, then adjust size and timeouts. The right pool size is the smallest one that keeps wait time near zero.

Quick Check

Test your understanding of connection pooling.

Recap

You learned to optimize database access with pooling:

  • Pools reuse connections to avoid per-request setup cost
  • Size pools by capacity (e.g. cores), not request volume
  • Always release; guard against leaks with timeouts and detection
  • Account for total connections across all instances; use poolers like PgBouncer at scale

Często zadawane pytania

Czy lekcja „Pula połączeń z bazą danych” jest bezpłatna?

Tak — pełny tekst „Pula połączeń z bazą danych” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu System Design Basics for Backend Developers, przejdź na CoddyKit PRO. Kurs System Design Basics for Backend Developers zawiera 4 lekcji w sumie.

Co nauczysz się w „Pula połączeń z bazą danych”?

Dowiedz się, jak pule połączeń eliminują koszt otwierania połączenia z bazą danych dla każdego żądania oraz jak dobrać i dostroić pulę pod kątem wydajności. Ćwiczysz System Design Basics for Backend Developers z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć System Design Basics for Backend Developers?

Nie wymagamy żadnego doświadczenia. System Design Basics for Backend Developers w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.

Ile czasu zajmuje lekcja „Pula połączeń z bazą danych”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji System Design Basics for Backend Developers?

Tak. Każda lekcja System Design Basics for Backend Developers zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Optymalizacja opóźnień i przepustowości
  2. Współbieżność i równoległość
  3. Testowanie wydajności i profilowanie
  4. Pula połączeń z bazą danych
← Powrót do System Design Basics for Backend Developers