Fix the cost model for a reused MongoDB client
Your task
Your Lambda opened a new MongoDB client on every request and closed it at the end. Latency was high, and Atlas showed constant connection churn. The fix creates the client once at module scope, so warm invocations in the same container reuse it. Your team wants a model that prices both versions.
An assistant wrote simulate_connection_cost(is_cold_start, handshake_ms, query_ms, reuse_client). It is in the editor. It has a bug. Find it and fix it.
Input and output:
is_cold_start: one entry per invocation, in order.truewhen that invocation runs in a new container.handshake_ms: the time it takes to open a connection (TCP, TLS and auth).query_ms: the time the query itself takes.reuse_client:truefor the module scope client,falsefor a client per request.- Return
[total_ms, connections_opened]for the whole run.
Rules the tests check:
- Every invocation pays
query_ms. - With
reuse_clientfalse, every invocation also opens a connection. - With
reuse_clienttrue, an invocation opens a connection only when its container does not hold one yet. The container then holds it for later invocations. - Opening a connection adds
handshake_msto the total and 1 toconnections_opened. - A cold start is a new container, which holds no connection. The first invocation's container also starts with none, even when it is not marked cold.
- An empty run returns
[0, 0].
Examples
simulate_connection_cost(is_cold_start: list[bool], handshake_ms: int, query_ms: int, reuse_client: bool) -> list[int]Example 1
Input
simulate_connection_cost([True, False, False], 120, 10, False)Output
[390, 3]Example 2
Input
simulate_connection_cost([True, False, False], 120, 10, True)Output
[150, 1]Example 3
Input
simulate_connection_cost([], 120, 10, True)Output
[0, 0]