Skip to main content

a2a_protocol_server/rate_limit/shared/
postgres.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`PostgresRateLimitCounter`]: the shared counter in a `PostgreSQL` table.
5
6use super::{A2aError, A2aResult, Future, Pin, RateLimitCounter};
7use std::sync::atomic::{AtomicU64, Ordering};
8
9/// The table the counter lives in.
10///
11/// `window_no` is part of the primary key rather than a column to
12/// overwrite, so a request arriving as the window turns lands in the new
13/// window's row instead of racing an update against the old one.
14///
15/// `window_secs` is the width `window_no` was numbered under. A table is
16/// shared by every component given this counter, and they do not all count in
17/// windows of one width (the rate limiter's default is 60 s and the
18/// authentication-failure throttle's is 300 s). `window_no` numbers of
19/// different widths are not comparable, so a sweep that does not know a row's
20/// width deletes another width's live rows: measured with the two statements
21/// below, a 60 s sweep removed a 300 s row whose count was 3.
22const CREATE_TABLE_SQL: &str = "CREATE TABLE IF NOT EXISTS a2a_rate_limit (
23        caller       TEXT   NOT NULL,
24        window_no    BIGINT NOT NULL,
25        request_count BIGINT NOT NULL,
26        window_secs  BIGINT NOT NULL DEFAULT 0,
27        PRIMARY KEY (caller, window_no)
28    )";
29
30/// Adds `window_secs` to a table an earlier release made.
31///
32/// A row written before the column existed has the default `0`, which a sweep
33/// treats as expired: the counts of a window or two are forgotten once, at
34/// the upgrade, which is what a restart already does to them.
35const ADD_WINDOW_SECS_SQL: &str = "DO $$ BEGIN \
36    IF NOT EXISTS (SELECT 1 FROM information_schema.columns \
37        WHERE table_schema = current_schema() AND table_name = 'a2a_rate_limit' \
38        AND column_name = 'window_secs') \
39    THEN ALTER TABLE a2a_rate_limit ADD COLUMN window_secs BIGINT NOT NULL DEFAULT 0; \
40    END IF; END $$";
41
42/// Count one request and return the new total, in one statement.
43///
44/// `INSERT .. ON CONFLICT DO UPDATE .. RETURNING` is what makes this
45/// atomic: `PostgreSQL` takes the row lock for the upsert and returns the
46/// post-increment value, so two replicas hitting the same row get 1 and 2
47/// rather than 1 and 1. A `SELECT` followed by an `UPDATE` would lose
48/// increments under precisely the concurrency this exists for.
49///
50/// The window is `floor(epoch / window_secs)` on the **database's** clock,
51/// not the number the interceptor computed from the replica's own:
52/// replicas whose clocks differ by a second would otherwise count in
53/// different rows for that second at every boundary, and each would admit
54/// a full limit.
55///
56/// `$2` is the window width in seconds.
57const COUNT_SQL: &str = "INSERT INTO a2a_rate_limit (caller, window_no, request_count, window_secs) \
58     VALUES ($1, floor(extract(epoch from now()) / $2::bigint)::bigint, 1, $2::bigint) \
59     ON CONFLICT (caller, window_no) \
60     DO UPDATE SET request_count = a2a_rate_limit.request_count + 1, \
61                   window_secs = EXCLUDED.window_secs \
62     RETURNING request_count";
63
64/// Drop rows of width `$1` for windows before the previous one, on the
65/// database's clock, and every row whose width is not recorded.
66///
67/// The previous window is kept: a count that was already past `now()` when
68/// the window turned lands in it, and a clock that steps back (a failover
69/// onto a host with a different clock) puts `now()` one window behind
70/// rows already written. Rows of another width are left to the sweep of that
71/// width (see [`CREATE_TABLE_SQL`]). `$1` is the window width in seconds.
72const SWEEP_SQL: &str = "DELETE FROM a2a_rate_limit \
73     WHERE (window_secs = $1::bigint \
74            AND window_no < floor(extract(epoch from now()) / $1::bigint)::bigint - 1) \
75        OR window_secs = 0";
76
77/// How many counts between sweeps of expired windows.
78///
79/// The same amortisation the in-process limiter uses for its bucket map,
80/// for the same reason: the table is bounded by callers-per-window, and
81/// without a sweep it would instead be bounded by callers-per-window times
82/// the age of the deployment.
83const SWEEP_INTERVAL: u64 = 1_000;
84
85/// A [`RateLimitCounter`] backed by a `PostgreSQL` table.
86///
87/// Suits a deployment already sharing a `PostgreSQL` task store: no second
88/// piece of infrastructure, and the counter is as available as the store
89/// the agent already depends on.
90///
91/// Windows are numbered by the database's clock, not the replica's, so
92/// replicas whose clocks differ still count in the same row and one
93/// replica's sweep cannot delete a window another is still counting in.
94///
95/// It is not the fastest possible shared counter — an in-memory keyspace
96/// like Redis will beat a durable table — and that is the trade being
97/// made. A deployment that needs the last microsecond implements
98/// [`RateLimitCounter`] against Redis instead; the trait exists so that is
99/// a few lines rather than a fork.
100pub struct PostgresRateLimitCounter {
101    pool: sqlx::PgPool,
102    counted: AtomicU64,
103}
104
105impl std::fmt::Debug for PostgresRateLimitCounter {
106    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107        f.debug_struct("PostgresRateLimitCounter")
108            .finish_non_exhaustive()
109    }
110}
111
112impl PostgresRateLimitCounter {
113    /// Connects to `url` and creates the counter table if it is absent.
114    ///
115    /// # Durability, deliberately traded away
116    ///
117    /// Sessions on this pool run with `synchronous_commit = off`, so an
118    /// increment is not waiting on a WAL fsync. Measured on loopback, that
119    /// is the difference between **598us and 232us per request** — the
120    /// fsync was almost two thirds of the cost.
121    ///
122    /// It is the right trade for this data specifically, and would not be
123    /// for most: a rate-limit count describes one window, is superseded
124    /// when the window rolls, and is swept away shortly after. The worst a
125    /// crash can do is forget that a caller had used part of its budget in
126    /// the last moments before it — which lets a few extra requests
127    /// through, once, on a server that has just restarted.
128    ///
129    /// The setting is scoped to the pool this constructor owns.
130    /// [`from_pool`](Self::from_pool) deliberately does *not* apply it: the
131    /// pool handed in there is usually the task store's, and quietly making
132    /// a task store non-durable to speed up a counter would be an
133    /// appalling thing to do behind a caller's back. A caller who wants
134    /// both can say so on their own pool.
135    ///
136    /// # Errors
137    ///
138    /// [`A2aError::internal`] if the database cannot be reached or the
139    /// table cannot be created.
140    pub async fn new(url: &str) -> A2aResult<Self> {
141        let pool =
142            crate::store::pg_retry::recycling_after_failover(sqlx::postgres::PgPoolOptions::new())
143                .after_connect(|conn, _meta| {
144                    Box::pin(async move {
145                        sqlx::query("SET synchronous_commit = off")
146                            .execute(&mut *conn)
147                            .await
148                            .map(|_| ())
149                    })
150                })
151                .connect(url)
152                .await
153                .map_err(|e| A2aError::internal(format!("rate-limit counter connect: {e}")))?;
154        Self::from_pool(pool).await
155    }
156
157    /// Uses an existing pool — the usual choice when the deployment already
158    /// has one for its task store, so the limiter adds no connections.
159    ///
160    /// Unlike [`new`](Self::new), this leaves the pool's settings exactly
161    /// as the caller configured them, including durability. That costs
162    /// roughly 2.8x per request against a pool with
163    /// `synchronous_commit = off`, and it is not this constructor's call to
164    /// make on a pool it does not own.
165    ///
166    /// # Errors
167    ///
168    /// [`A2aError::internal`] if the table cannot be created.
169    pub async fn from_pool(pool: sqlx::PgPool) -> A2aResult<Self> {
170        // Under the crate's schema lock, so replicas starting against an
171        // empty database do not race. See `store::pg_schema`.
172        crate::store::pg_schema::apply(&pool, &[CREATE_TABLE_SQL, ADD_WINDOW_SECS_SQL])
173            .await
174            .map_err(|e| A2aError::internal(format!("rate-limit counter migrate: {e}")))?;
175        Ok(Self {
176            pool,
177            counted: AtomicU64::new(0),
178        })
179    }
180
181    /// Deletes rows for windows before the previous one, as the database
182    /// numbers them for windows `window_secs` wide.
183    ///
184    /// Failure is traced and swallowed: a sweep that did not happen costs
185    /// disk, while an error propagated from here would reject a request
186    /// that was correctly counted.
187    async fn sweep(&self, window_secs: i64) {
188        if let Err(_e) = sqlx::query(SWEEP_SQL)
189            .bind(window_secs)
190            .execute(&self.pool)
191            .await
192        {
193            trace_warn!(error = %_e, "rate-limit counter sweep failed");
194        }
195    }
196}
197
198impl RateLimitCounter for PostgresRateLimitCounter {
199    fn count<'a>(
200        &'a self,
201        key: &'a str,
202        _window: u64,
203        window_secs: u64,
204    ) -> Pin<Box<dyn Future<Output = A2aResult<u64>> + Send + 'a>> {
205        Box::pin(async move {
206            let window_secs = i64::try_from(window_secs)
207                .map_err(|_| A2aError::internal("rate-limit window out of range"))?;
208
209            let (count,): (i64,) = sqlx::query_as(COUNT_SQL)
210                .bind(key)
211                .bind(window_secs)
212                .fetch_one(&self.pool)
213                .await
214                .map_err(|e| {
215                    crate::store::pg_retry::note_read_only(&e);
216                    A2aError::internal(format!("rate-limit counter: {e}"))
217                })?;
218
219            let n = self.counted.fetch_add(1, Ordering::Relaxed);
220            if n > 0 && n.is_multiple_of(SWEEP_INTERVAL) {
221                self.sweep(window_secs).await;
222            }
223
224            Ok(u64::try_from(count).unwrap_or(u64::MAX))
225        })
226    }
227}
228
229#[cfg(test)]
230mod tests;