Fix the peak connection count for serverless functions

Review the AI's codeEasy10 minGoogle style

Your task

Your Cloud Function opened a new Postgres connection on every HTTP request and never closed it. Under traffic, Postgres refused new clients with too many clients already. The team has two fixes: close each connection after use, and put a connection pooler in front of the database. A pooler, such as PgBouncer, shares a small pool of database connections among many clients. You model how many connections Postgres sees at peak.

An assistant wrote peak_db_connections(instances, requests_per_instance, close_after_use, pooler_limit). It is in the editor. It has a bug. Find it and fix it.

Input and output:

  • instances: how many function instances run at the same time. An integer. It can be 0 or negative.
  • requests_per_instance: how many requests each instance handles at peak. An integer. It can be 0 or negative.
  • close_after_use: true when each request closes its connection when it finishes.
  • pooler_limit: the pool size of the pooler. 0 or less means there is no pooler.
  • Return the peak number of connections Postgres sees, as an integer.

Rules the tests check:

  • If instances or requests_per_instance is 0 or less, return 0.
  • The demand is the number of connections the instances hold:
    • With close_after_use true, each instance holds 1 connection at a time, so the demand is instances.
    • With close_after_use false, every request leaks its connection, so the demand is instances times requests_per_instance.
  • With a pooler (pooler_limit above 0), Postgres never sees more than pooler_limit connections. Return the smaller of the demand and pooler_limit.
  • Without a pooler, return the demand.

Examples

peak_db_connections(instances: int, requests_per_instance: int, close_after_use: bool, pooler_limit: int) -> int
Example 1
Inputpeak_db_connections(200, 5, False, 0)
Output1000
Example 2
Inputpeak_db_connections(200, 5, True, 0)
Output200
Example 3
Inputpeak_db_connections(200, 5, False, 20)
Output20