Fix the peak connection count for serverless functions
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
instancesorrequests_per_instanceis 0 or less, return0. - The demand is the number of connections the instances hold:
- With
close_after_usetrue, each instance holds 1 connection at a time, so the demand isinstances. - With
close_after_usefalse, every request leaks its connection, so the demand isinstancestimesrequests_per_instance.
- With
- With a pooler (
pooler_limitabove 0), Postgres never sees more thanpooler_limitconnections. Return the smaller of the demand andpooler_limit. - Without a pooler, return the demand.
Examples
peak_db_connections(instances: int, requests_per_instance: int, close_after_use: bool, pooler_limit: int) -> intExample 1
Input
peak_db_connections(200, 5, False, 0)Output
1000Example 2
Input
peak_db_connections(200, 5, True, 0)Output
200Example 3
Input
peak_db_connections(200, 5, False, 20)Output
20