Skip to content

Gateway permanently fails all requests for a user after a dynamic-config refresh flips the connection-pool key ("Connection pool missing for user.") #720

Open

Description

@morch23mj

Summary

After pg_documentdb_gw's periodic dynamic-configuration refresh runs (default interval 60*5 = 300s, see configuration/setup.rs), every subsequent request from an already-authenticated data-plane user can start failing with the internal error "Connection pool missing for user." — and it never recovers on its own. The user's connection pool is still present in user_data_pools and perfectly healthy; it's just filed under a cache key that the per-request lookup will never recompute back to. The client only sees a generic server-origin error (the gateway returns an error document with ok: 0), so this is not a client-side bug.

Environment

  • Image: documentdb-local v0.114-0 (built 2026-07-17), the latest release at the time of writing.
  • DynamicConfigurationRefreshIntervalSecs left at the built-in default (60 * 5 seconds — SetupConfiguration::dynamic_configuration_refresh_interval_secs, configuration/setup.rs).
  • Client: a long-lived Mongo-wire client, authenticating as a fixed data-plane user and issuing periodic authenticated requests.
  • Observed over ~17h on a long-running deployment: the failure recurs phase-locked to the 300s refresh timer — roughly 4m35s of healthy service, then failing until the client reconnects / the process restarts.

Root cause

PgPoolSettings (postgres/conn_mgmt/pool_settings.rs) derives Hash/Eq over six fields:

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub struct PgPoolSettings {
    max_connections: usize,
    system_connection_budget: usize,
    connection_buffer_size: usize,
    connection_pruning_interval: Duration,
    connection_idle_lifetime: Duration,
    connection_lifetime: Duration,
}

from_configuration() builds this struct fresh from the live dynamic configuration on every call:

pub fn from_configuration(config: &dyn DynamicConfiguration) -> Self {
    let max_connections = config.max_connections();
    ...
}

max_connections is read from a live Postgres GUC every dynamic-config refresh, via PgConfiguration::max_connections() (configuration/pg_configuration.rs):

fn max_connections(&self) -> usize {
    let max_connections = self.get_i32("max_connections", -1);
    match max_connections {
        n if n < 0 => {
            // theoretically we can't end up here, since Postgres always provide values
            tracing::error!("GUC max_connections is not setup correctly");
            25usize
        }
        n => usize::try_from(n).unwrap_or(25),
    }
}

On a bad/transient read this silently substitutes 25. (The same code path also fires on any legitimate runtime change to the max_connections GUC, e.g. an operator running ALTER SYSTEM SET max_connections = ...; SELECT pg_reload_conf(); — that's an intentional, tested behavior; see validate_max_conn_change in pool_manager.rs's test module.) Either way, once this value changes, PgPoolSettings's hash changes too.

The refresh itself runs on PgConfiguration's background timer (start_dynamic_configuration_refresh_thread, configuration/pg_configuration.rs), on the interval configured by dynamic_configuration_refresh_interval_secs (default 60*5, configuration/setup.rs), calling refresh_configuration() which swaps in the new value map and reloads the topology snapshot.

PoolManager::get_data_pool (postgres/conn_mgmt/pool_manager.rs) recomputes (username, PgPoolSettings) on every request and does an exact-key lookup:

pub fn get_data_pool(
    &self,
    username: &str,
    dynamic_configuration: &dyn DynamicConfiguration,
) -> Result<Arc<ConnectionPool>> {
    let settings = PgPoolSettings::from_configuration(dynamic_configuration);

    match self.user_data_pools.get(&(username.to_owned(), settings)) {
        None => Err(DocumentDBError::internal_error(
            "Connection pool missing for user.".to_owned(),
        )),
        Some(pool_ref) => {
            let pool = Arc::clone(pool_ref.value());
            pool.touch();
            Ok(pool)
        }
    }
}

Once settings no longer matches the key the pool was inserted under, this misses — permanently, since nothing ever re-inserts under the old key, and nothing recomputes the new key's entry either, because allocate_data_pool (the only function with the user's password, needed to build a new pool) only runs during authentication, not on this per-request path. Every request for that user fails from that point on, until the client reconnects (forcing re-authentication) or the gateway process restarts.

For contrast, get_system_shared_pool in the same file does self-heal on a settings-key miss:

match self.shared_data_pools.entry(settings) {
    Entry::Occupied(pool_ref) => { ... }
    Entry::Vacant(entry) => {
        let system_shared_pool = Arc::new(ConnectionPool::new_with_user(
            self.setup_configuration.as_ref(),
            &self.query_catalog,
            self.setup_configuration.postgres_data_user(),
            self.setup_configuration.postgres_data_user_password(),
            ...
        )?);
        entry.insert(Arc::clone(&system_shared_pool));
        Ok(system_shared_pool)
    }
}

This works because the shared pool uses system-known credentials (setup_configuration.postgres_data_user() / postgres_data_user_password()), which are always available. get_data_pool's user path has no equivalent: the actual user password is never held outside of the allocate_data_pool authentication call, so there is nothing it could use to build a replacement pool inline.

Steps to reproduce

  1. Run pg_documentdb_gw (documentdb-local v0.114-0) against a Postgres backend with the default DynamicConfigurationRefreshIntervalSecs (300s).
  2. Authenticate a client as a data-plane user/password and keep issuing periodic authenticated requests (as a long-lived service would).
  3. While the client is connected, cause the max_connections GUC value observed by the gateway's next refresh to change — either genuinely (ALTER SYSTEM SET max_connections = <new>; SELECT pg_reload_conf();) or via a transient failure of the pg_settings query that the refresh issues (see PgConfigurationInner::load_configurations), which triggers the silent-25 fallback in max_connections().
  4. Wait for the next dynamic-config refresh tick (up to 300s by default).
  5. Issue another authenticated request as the same user.

Expected behavior

The request succeeds. The user's existing connection pool is still healthy; a change in max_connections (real or an artifact of a bad GUC read) should not invalidate the client's ability to keep using it.

Actual behavior

The request — and every subsequent one from that user — fails immediately with the internal error "Connection pool missing for user.", surfaced to the client as a generic error document (ok: 0) originating from the server, which rules out a client-side cause. The failure recurs phase-locked to the 300s refresh interval — roughly 4m35s healthy, then failing — and only a client reconnect (re-authentication) or a process restart clears it.

Log evidence

The gateway logs the topology/config refresh via tracing::info!("Topology acquired: {doc:?}") in PgConfiguration::load_topology (configuration/pg_configuration.rs), which runs as part of every refresh_configuration() call. This line reliably precedes the first "Connection pool missing for user." error by roughly 10 seconds — consistent with the refresh completing, the pool key shifting, and the next incoming request from the still-connected client hitting the stale-key miss shortly after (representative excerpt):

...  INFO documentdb_gateway_core::configuration::pg_configuration: Topology acquired: PgDocument { ... }
...  (≈10s later)
...  ERROR documentdb_gateway_core::...: Connection pool missing for user.

Possible duplicate

This may overlap with #379 ("[Feature Request] Automatically retry writes on the gateway"), which is about gateway resilience when the backing Postgres is unavailable during failover. That issue's failure mode (PG actually down) is different from this one (PG is up and the user's pool is healthy — only an internal cache key is stale), but both concern the gateway hard-failing user requests instead of tolerating a transient/self-correcting backend condition. Flagging for maintainers to check for duplication or overlap in the underlying fix.

Additional context

This investigation (log correlation, root-cause tracing through the config-refresh → pool-key → pool-manager path, and the reproduction steps above) was prepared with substantial AI assistance and reviewed by the author before submission.

Activity

  1. added
    gateway
    on Aug 13, 2026
  2. documentdb-triage-tool commented on Aug 13, 2026

    @documentdb-triage-tool

    🤖 Auto-triaged by documentdb-triage-tool.

    Applied: gateway, bug
    Project fields suggested: Component gateway · Priority P1 · Effort M · Status Triage
    Confidence: 0.90 (llm)

    Reasoning

    LLM: Gateway permanently breaks all requests for authenticated users after each dynamic-config refresh due to a stale connection-pool cache key, requiring process restart to recover — an active blocker for long-running deployments.

    If a label is wrong, remove it manually and ping @patty-chow so the rules can be tuned. The bot will not re-label items that already have component labels.

  3. moved this from Todo to In Progress in Issue triageon Aug 13, 2026
  4. self-assigned this
    on Aug 13, 2026
  5. AndrewKhoma commented on Aug 17, 2026

    @AndrewKhoma
    Member

    Can you elaborate more on these steps of reproduction, since it's still unclear to me who would orchestrate the system in this way. What are the use cases?

    If someone have to change this postgres startup guc in the same running docker container, then why there's no either impactful maintenance when you need to stop both gateway and postgresql to read the new values respectfully or Impactless maintenance when the new docker is up and running with the new GUC have been created and the traffic was redirected to the new container

  6. documentdb-triage-tool commented on Aug 31, 2026

    @documentdb-triage-tool

    👋 @tsharp — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  7. documentdb-triage-tool commented on Sep 15, 2026

    @documentdb-triage-tool

    👋 @tsharp — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  8. documentdb-triage-tool commented on Sep 29, 2026

    @documentdb-triage-tool

    👋 @tsharp — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  9. documentdb-triage-tool commented on Oct 13, 2026

    @documentdb-triage-tool

    👋 @tsharp — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  10. documentdb-triage-tool commented on Oct 28, 2026

    @documentdb-triage-tool

    👋 @tsharp — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

  11. documentdb-triage-tool commented on Nov 11, 2026

    @documentdb-triage-tool

    👋 @tsharp — this issue has been assigned for 14 days with no activity. Is it still in progress? If you've made progress, please leave a quick update. Otherwise it'll be flagged for re-assignment at the next triage meeting.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

buggateway

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions