DBTrail

Which side answers a statement

On the PostgreSQL port, what your PostgreSQL answers, what the copy answers, how to check which one did, and what is refused.

A statement on the PostgreSQL port is answered either by your PostgreSQL, read-only, or by DBTrail's copy. The short version comes first: what decides it, how to check who answered, and what is refused before it reaches your PostgreSQL. Every rule in full follows, with the port's worker for short statements, its memory and its status.

Who answers a statement

From 0.140.0 the port serves a server only when it can forward (the two ways).

  1. A transaction block goes to your PostgreSQL, every statement in it.

  2. A statement the copy is not known to answer as PostgreSQL does goes to your PostgreSQL. For example now(), or text sorted by order.

  3. Of what the copy can answer, only what is expensive on your PostgreSQL goes to the copy. New in 0.138.0. The copy has no index: reading one row of a 2-million-row table by its key took 15 seconds there, against about a millisecond on PostgreSQL. So the port first asks your PostgreSQL for the statement's plan (EXPLAIN (FORMAT JSON); the statement itself does not run), and sends it to the copy only when:

    • the plan's Total Cost is 50,000 or more, or
    • the plan has a sequential scan estimated at 1,000,000 rows or more, whatever its cost.

    Anything else is answered by your PostgreSQL, by its indexes.

  4. An expensive statement stays on the copy even where the copy may answer it a little differently (from 0.140.0, for a statement sent without preparing it). Rule 2 then applies only to cheap statements. The answer can differ in the last decimals of an average or a division, or in the order of text. For your PostgreSQL's own answer, send the statement inside a transaction block. In full.

With the user DBTrail connects with, whatever goes to your PostgreSQL first has to pass that user's check. What does not pass is refused, or answered by the copy when the copy can answer it.

The two thresholds are settings of the PostgreSQL port:

Docker .envOption fileOut of the box
Plan costPG_ROUTER_COST_THRESHOLDpg-router-cost-threshold50000
Rows of a sequential scanPG_ROUTER_SCAN_ROWSpg-router-scan-rows1000000

0 turns one rule off; both cannot be 0.

What to know:

  • It costs one round trip to your PostgreSQL for each statement the copy could answer. A connection remembers the verdict on a statement shape for a minute when every value in it is compared with = and the plan is ten times below both thresholds, so a read by key with another key is not asked about again.
  • The plan's numbers are estimates, as fresh as your PostgreSQL's statistics (ANALYZE).
  • When all of the port's connections to your PostgreSQL are taken, a statement waits for one, up to 30 seconds or its statement_timeout, and gets error 53300 only then.
  • When your PostgreSQL cannot be reached, a statement the copy can answer is answered by the copy, with a NOTICE.
  • On PostgreSQL 15 a prepared statement with parameters goes to your PostgreSQL, however expensive: asking for its plan needs GENERIC_PLAN, which PostgreSQL 16 and later have.
  • A result larger than the copy's row cap goes to your PostgreSQL (from 0.139.1), which then runs that read in full. SELECT * FROM orders on a large table now returns every row instead of error 54000. This holds where the plan's row count can be trusted: one table read alone, whole or by an index, with nothing checked row by row, under a LIMIT or a sort at most. With a filter no index serves, a join, an aggregate, GROUP BY, DISTINCT, a window or a UNION, the copy still tries it and can still answer 54000. A LIMIT at or under the cap stays on the copy, and a prepared statement with parameters is never sent to your PostgreSQL for its size.
  • Some forms the copy answers differently go to your PostgreSQL (from 0.139.1): text sorted by a position or by a name the statement gave it, substring with a start of zero or below, date and time literals outside the plain YYYY-MM-DD and HH:MM:SS forms, and arithmetic or sum() over a real column. From 0.140.0 this holds for a cheap statement; an expensive one stays on the copy (rule 4 above).

A value never reads back in time

The copy is a second or two behind your PostgreSQL in fresh mode. A counter your PostgreSQL showed a connection as 37413 could read 37405 on the copy the next moment. The port does not let that happen.

Once your PostgreSQL answered a connection about a table, a statement for the copy that reads that table on the same connection waits for the copy to catch up: up to 6 seconds, and never past its statement_timeout. Then the copy answers. When the copy cannot get there in time, your PostgreSQL answers at once and the copy runs nothing.

It holds per connection: an application that writes on one connection and reads on another is not covered, and during an update of the recent changes that other connection may read the version from before it.

The rule holds table by table. A statement that reads other tables is answered by the copy at once. So two answers on one connection about different tables can be of different moments:

SELECT balance FROM accounts WHERE id = 7;   -- cheap: your PostgreSQL answers, as of now
SELECT sum(amount) FROM payments;            -- expensive: the copy answers, a second or two behind

A payment committed together with a change of that balance can be in the first answer and not in the second. A value of one table still never goes back: after your PostgreSQL showed accounts, a report that reads accounts waits for the copy. To read two tables at one moment, read them in one statement, or in a transaction block, which your PostgreSQL answers whole.

  • A table read from its snapshot alone (fast mode, or a table with no recent changes) goes to your PostgreSQL on such a connection.
  • When the port cannot prove which tables a statement read (a view, a partitioned table, a function of yours, a cursor, several statements in one text, among others), the statement counts as having read every table, and the rule covers the whole connection. Every case: which side answers a statement.
  • While it waits, a statement holds its connection to the port and nothing else.

Check who answered: SHOW dbtrail.router_status

New in 0.138.0. On any connection to the port, this statement says which side answered that connection's last statement, and why:

SELECT count(*) FROM orders WHERE now() IS NOT NULL;
SHOW dbtrail.router_status;
           name           |                                     value
--------------------------+--------------------------------------------------------------------------------
 server                   | a9d50e10e73cb3b4
 forwarding               | on
 sql_mode                 | fast
 copy_snapshot            | 2026-11-21T00:42:49Z
 copy_age_seconds         | 1
 last_answer              | source
 last_answer_reason       | veto
 last_answer_reason_means | something in the statement is not known to answer on the copy as on PostgreSQL
 last_answer_error        | no
 counting_since           | 2026-11-21T00:42:50Z
 statements_copy          | 1
 statements_source        | 12
 statements_refused       | 1
 reason_answers_the_same  | 1
 reason_veto              | 9
RowWhat it says
serverThe id of the server this connection reads
forwardingon when statements of this connection may go to your PostgreSQL, off when the copy answers alone, which a served server does only when it hides tables or columns. forwarding_off_reason then says why
forwarding_accountThe account statements are sent with: forwarding user <name>, or capture account, read-only, tables of the copy only, or none
sql_modefresh or fast
copy_snapshot, copy_age_secondsWhen the newest snapshot was taken, and how long ago that is. unknown before the first snapshot. In fresh mode an answer also reads the changes captured since
last_answercopy, source, refused, or none before the first statement
last_answer_reason, last_answer_reason_meansWhy: one of the reasons below, then the same in a sentence
last_answer_errorWhether the client got an error for it
last_answer_indexed_through, last_answer_age_secondsWhen the copy answered: how old the data it read was. unknown for an answer that read a table without its newest changes, as in fast mode
counting_since, statements_copy, statements_source, statements_refused, reason_<name>The server's counts since the port started
  • The port answers it itself, always: inside a transaction block, and in a failed block too, where it tells which side failed the block. It is never sent to your PostgreSQL or to the copy, and it does not count as an answer.
  • Send it alone. In one message with other statements (psql -c "SELECT 1; SHOW dbtrail.router_status") the whole message is refused with error 0A000 and nothing in it runs.
  • SHOW ROUTER STATUS is refused here, with the statement to send instead.

The reasons:

Who answeredReasonWhy
copyanswers_the_sameIt answers on the copy as on PostgreSQL, and its plan on your PostgreSQL is expensive
copycopy_commandA command of the copy's own (SHOW TABLES, DESCRIBE)
copyhidden_rulesThe server hides tables or columns: nothing is sent to its source
copycapture_gateNew in 0.138.0. The server forwards with the user DBTrail connects with, and the statement did not pass that user's check, so the copy answered it without asking for its plan
sourcecheap_planNew in 0.138.0. Its plan is under both thresholds
sourceexplain_failedNew in 0.138.0. Its plan could not be had (your PostgreSQL refused the EXPLAIN, or the text holds more than one statement). Your PostgreSQL answers it, its error included
sourcein_transactionThe client's transaction block
sourcevetoSomething the copy answers differently, or is not known to answer the same
sourcesession_differsA session setting the copy is not known to reproduce (TimeZone)
sourcenot_a_selectEXPLAIN, a cursor, a savepoint, VALUES
sourcecatalog_not_on_copyA catalog statement the copy does not answer
sourcetable_not_on_copyA table the copy does not hold
sourcecopy_refusedThe copy could not run it
sourcecopy_columns_differA column the copy writes otherwise (a numeric without precision)
sourceresult_over_row_capNew in 0.139.1. Its plan says it returns more rows than the copy's cap
sourcecopy_behind_source, copy_age_unknownThe server's lag limit
sourcecopy_queue_full, copy_wait_timeoutThe copy was busy
refusedread_onlyNot a read

The port's /status also counts copy_too_old (the copy could not catch up within the wait above, so your PostgreSQL answered) and source_unreachable (your PostgreSQL could not be asked, so the copy answered).

Refused before it reaches your PostgreSQL

The port reads a statement the way PostgreSQL reads it before sending it, and does not send what it cannot read with certainty. From 0.138.0 it refuses some statements it used to send:

  • A text it cannot read with certainty (a quote or a comment left open): error 0A000.
  • Statements that begin as a read and are not one (error 25006): SELECT ... INTO, a SELECT that locks its rows (FOR UPDATE, FOR SHARE), an INSERT, UPDATE, DELETE or MERGE inside or after a WITH list, and EXPLAIN of anything but a query. In a WITH, an EXPLAIN or a DECLARE, a column or alias named insert, update, delete or merge has to be written in double quotes.
  • Functions that act beyond a read, such as stopping or cancelling a session, reading the server's files, nextval and setval, txid_current and pg_logical_emit_message.

Every one: the forwarding user.

Every rule in full

With a forwarding user, a statement outside a transaction block is answered by the copy only when everything in it is something the copy is known to answer the way PostgreSQL does. What "known" means is measured, not assumed: the comparison harness (internal/pgcompare) runs the same statements on a real PostgreSQL and on its copy, and only what it found answering the same is let through. When in doubt, a cheap statement goes to the source: the cost is a slower answer, never a different one.

An expensive statement goes to the copy even where it may answer otherwise. Since 0.140.0, a statement sent without preparing it (the simple protocol: psql, and drivers that put the values in the text themselves) whose plan on the source is over the port's cost thresholds (--cost-threshold, --scan-rows) is answered by the copy, even when the list below would send it to the source. Such an answer can differ from PostgreSQL's: text sorted by bytes instead of by the database's collation (and, under LIMIT, other rows), the last decimals of a division or an average, a char(n) compared with a string that ends in blanks, a now() read on the copy, a name given in the select list and used in WHERE. The port counts these under heavy_on_copy on /status. A statement the copy cannot run at all still goes to the source, and the client does not see the copy's error. A cheap statement, one inside a transaction block, one under a session time zone, and a prepared statement (the extended protocol) are decided as before. For the answer PostgreSQL gives, send the statement inside a transaction block (BEGIN; ...; COMMIT;): every statement of a block is the source's.

The source answers a cheap statement for:

  • A function, operator, cast or construct the copy answers differently or not at all. The copy takes count, sum, min, max, coalesce, nullif, greatest, least, length, substring (with its start, and its length when given, written as whole numbers above zero: substring(name, 1, 3), substring(name FROM 2 FOR 3)) and substr under the same rule (substr(name, 1, 3)), also of a char(n) column, whose padding the copy keeps: where the cut reaches it the copy answers b and PostgreSQL b, and a comparison of that cut (substr(code, 1, 3) = 'b') can miss the row on the copy; a cut inside the part with data is the same on both. trim, position, concat, abs, mod(x, n) of integer, bigint or numeric columns and numbers by a whole number written in the statement (not 0 or -1), ascii of text whose first character is below 128, bool_and, string_agg, row_number, rank, lag, and extract, date_part and date_trunc of a year, month or day (date_trunc of a timestamp or a timestamp with time zone column, written with or without its table: a series by day over a timestamptz stays on the copy, in a session in UTC, the only one the copy answers in); round(a / b, k) and round(avg(x), k) (also round(100 * avg(x), k), or any other power of ten) where k is written as a whole number from 0 to 15 (counting the power of ten of avg) and a, b and x are numerics or whole numbers, rounded as PostgreSQL rounds a numeric: half away from zero, to exactly k decimals (50.00); round(x, k) of any other numeric or whole number, with k from -38 to 15 (round(12.50, 3) is 12.500, round(5, 2) is 5.00, round(-5.0, -1) is -10), and round(x) and round(a / b) of a numeric; a CASE or COALESCE around such a round, checked value by value (PostgreSQL writes CASE WHEN c THEN round(x, 2) ELSE 0 END as 0 where the copy would write 0.00, so a row that takes the 0 sends the statement to the source); a division a / b and avg(x) written without a round(), of numerics and whole numbers: the exact quotient rounded to 16 decimals, a numeric as PostgreSQL's is. PostgreSQL writes its own with 16 significant digits or more, so the two are the same number with other decimals. The copy always writes 16; PostgreSQL's count depends on the value and on both sides: often 16 for a quotient from 1 to 9999 (7.5000000000000000, the same text), 12 for a larger one, 20 for a smaller one (0.3333333333333333 for 0.33333333333333333333), and 20 for 2.00 / 2. A quotient that ends within 16 decimals is exact (0.3 / 3 is 0.1000000000000000). A quotient under 0.000001 that is not zero is answered by the source, because 16 decimals would keep too few of its digits. A quotient that does not end is cut at the sixteenth decimal here and later on PostgreSQL, and what is worked out from it carries that: a comparison, a sort, a sum or a GROUP BY that turns on a digit past the sixteenth can come out otherwise on the copy. amount / 3 = 33333.333333333333 can match a row on one side and not on the other, a / b * b = a can be true on one and false on the other, and a GROUP BY a / b of two quotients that differ only past the sixteenth decimal can be one group on one side and two on the other. Write round(a / b, k) or round(avg(x), k) for PostgreSQL's text exactly. The copy answers when the statement shows each side to be a numeric or a whole number: numbers, columns of whole numbers or of a numeric of at most 20 digits and 8 decimals, +, -, *, parentheses, count, sum, min, max, abs, coalesce, nullif, greatest, least and length over them, and a CASE whose values are such (sum(CASE WHEN c THEN amount ELSE 0 END) / sum(amount), a share of a total): its conditions do not count, a NULL among its values takes the others' type, and a value of another type sends the statement to the source. A divisor of zero is PostgreSQL's error, from the source; floor(a / b) of numerics, as PostgreSQL takes it (95, not 95.0); ntile(n); extract(epoch from x) of a timestamp (a numeric with six decimals, as on PostgreSQL 14 and later) and to_timestamp(n) of a whole number of seconds, so to_timestamp(floor(extract(epoch from x) / 600) * 600) buckets as PostgreSQL does; the operators =, <>, <, >, <=, >=, +, -, *, ||, LIKE (a pattern without a backslash), IN, BETWEEN, IS [NOT] DISTINCT FROM, ANY, EXISTS, an array subscript by a positive whole number; ::date and CAST(... AS date); INTERVAL literals, and DATE, TIMESTAMP and TIME literals written in one form: a date as YYYY-MM-DD, a time as HH:MM or HH:MM:SS with at most six decimals and an hour below 24, a timestamp as the date alone or the date, a blank or a T, and the time (DATE '2026-01-05', TIMESTAMP '2026-01-05 10:30:00.123456'). A string written in the statement and compared with a date, timestamp or time column (=, <, BETWEEN, IN) is held to the same form; a value that arrives as a parameter of a prepared statement is not read by this rule; joins, GROUP BY, HAVING, DISTINCT [ON], UNION, INTERSECT, EXCEPT, WITH, window functions, FILTER, LIMIT and OFFSET. Anything else goes to the source. Some of what the harness found answering otherwise, and why each one goes there: a division of two whole numbers other than a column over a number (sum(qty) / count(*): PostgreSQL divides them as whole numbers, and the copy's division answers a numeric), a division or an avg() with a side the statement does not show to be a numeric or a whole number (a double precision or a real, a numeric without precision or past 20 digits or 8 decimals, a name from a subquery or a WITH (except as the argument of an avg(), when every definition of that name in the statement is a numeric or a whole number and no column has the name), sum() of a bigint, which PostgreSQL sums to a numeric, a function not in the list above, a CASE with such a value or with only NULL, a cast, a parameter), a division with a CASE just before or after its slash (CASE ... END / 2; in parentheses it is read), a division more than two deep in others (a / b / c / d), a division in LIMIT or OFFSET or inside ceil or trunc (the quotient could fall on the other side of the cut), avg(DISTINCT x) and an avg with FILTER or OVER, a round of a division of two whole numbers (PostgreSQL divides them as whole numbers), a round whose quotient lands so close to a half that PostgreSQL's own rounding of the division could reach it (the copy refuses it, and it goes to the source), round() of a double precision (it rounds a half to even) and of a whole number (a double precision on PostgreSQL), a round beside other values in one column (UNION, VALUES, ARRAY, greatest, least, nullif: PostgreSQL keeps each value's own decimals), a division by a zero written in the statement (PostgreSQL fails it), ~ and SIMILAR TO (the copy matched no row), -> and ->> (PostgreSQL answers json, and writes a nested value with spaces), a number with an exponent (a numeric on PostgreSQL), ::text of a float, substring with a start of zero or below, or one that is not a number written in the statement (substring('apple', -1, 3) is a on PostgreSQL; the copy counts a negative start from the end and answers e; left, right and overlay always go to the source), a date or time literal in any other form ('26-01-05'::date is 2026-01-05 on PostgreSQL and the year 26 on the copy, a seventh decimal of a second is rounded there and cut here, TIME '24:00:00' is a time there and midnight here), arithmetic (+, -, *, /) and sum() over a real column (PostgreSQL computes it as a double precision, so r + 1 with r = -0.1 is 0.8999999985098839 there and 0.9 on the copy, and answers sum(r) as a real; a real that is only read, compared, counted or taken the min or max of stays on the copy, and so does arithmetic over a double precision, a whole number or a numeric), a DATE, TIMESTAMP or TIME literal written with a time zone (TIMESTAMP '2026-03-02 10:00:00+02': the type holds none and PostgreSQL does not read it, so the literal is 10:00 there) and a string with one in either bound of a BETWEEN on a timestamp column, upper, lower and ILIKE (PostgreSQL folds case by the database's character type), COLLATE, AT TIME ZONE, FOR UPDATE, jsonb operators, generate_series and every function the list does not name.
  • The clock and the session: now(), CURRENT_DATE, CURRENT_TIMESTAMP, LOCALTIMESTAMP, current_user and the like. The copy's data is as old as its last update, and its clock and session are not the source's.
  • Text sorted or compared by order (an ORDER BY of text anywhere but the main statement, min() of one, name > 'B'): PostgreSQL orders text by the database's collation, the copy by bytes. The ORDER BY of the main statement is the exception, and the copy answers it, by a text column, an expression, a position or an alias, with or without LIMIT: the same rows, sorted by bytes (B, a, c where PostgreSQL writes a, B, c), and with a LIMIT or an OFFSET the rows kept can be other rows. To have PostgreSQL's order, write COLLATE "default" on the key (ORDER BY name COLLATE "default"): the statement goes to the source. A column the copy holds as text and PostgreSQL does not (an enum, a domain, money, inet, json, a numeric wider than 38 digits) sorts by its meaning on PostgreSQL, so when a statement reads one, only a key that is a real text column written by its name stays on the copy. A char(n) column sorted, a window, string_agg(x ORDER BY y), DISTINCT ON and an ORDER BY inside a subquery or a WITH stay with the source, where the order decides a value or which rows are counted. On a server without a forwarding user nothing changes. Text compared for equality, grouped or matched with LIKE stays on the copy. A sort key that is one call of count, sum, rank and the like is a number whatever text the statement reads elsewhere (ORDER BY sum(amount) DESC beside a selected name stays on the copy), and the field of a date_trunc or a date_part ('day') is not text. The port finds the text by what the statement names, and reads three ways of sorting text that name none. A position behind a *: in SELECT * FROM t ORDER BY 2, one table and nothing else, the port looks the position up in the table's columns, so it goes to the source when the second column is text and stays on the copy when it is a number or a date; in any other statement with a * in a select list (a join, a subquery, a WITH, a UNION, parentheses around the SELECT), an ORDER BY by position goes to the source when the rows under the * may hold text, whichever column the position is, and stays when they hold none. A name the statement gives a value that is also a text column's name (SELECT name AS name ... ORDER BY name, min(name) AS name, quoted or not; a name given to a number, sum(qty) AS qty, stays). And a text column named like a word of ORDER BY (ORDER BY last, ORDER BY first DESC). A name the statement gives a value itself (SUM(x) AS units, a column of a WITH or a subquery, read as s.units) is judged by what it stands for: a count, a sum, an average, a rank, arithmetic, a CASE that answers only numbers, or a number column renamed is not text; anything else may be, and goes to the source when it is sorted or compared by order.
  • A char(n) column used where its trailing blanks count. PostgreSQL pads a char(n) value with blanks ('ab' in a char(5) is 'ab '), ignores them when it compares, and drops them when the value becomes text (length, ||, a comparison with a text column, a UNION with one). The copy holds the value as text with its blanks, and counts them: WHERE code = 'ab' finds three rows on PostgreSQL and none on the copy, length(code) is 2 there and 5 here. The port reads each column's type on the source from the snapshot, and the source answers every statement that names a char(n) column anywhere but in one place: as a whole item of the select list of a statement that is one SELECT and nothing else, no subquery, WITH, UNION, INTERSECT or EXCEPT (SELECT id, code FROM t WHERE id = 7, with or without the table's name before it and an alias after it), and as a whole key of that statement's GROUP BY (SELECT status, count(*) FROM t GROUP BY status, the key selected or not): every value of a char(n) has the same length, so both sides make the same groups. A bpchar declared without a length keeps each value's own blanks and is not grouped by the copy. There both sides write the same padded value, and nothing reads it again under another name: the alias written a second time, a NATURAL JOIN, the table's name used as a value (count(DISTINCT t)), TABLE t inside a larger statement and a list that renames the columns (t AS a(i, x)) go to the source as well. So a comparison (=, <>, <, BETWEEN, IN, LIKE, IS DISTINCT FROM, IS NULL), a join's condition or USING, a GROUP BY of an expression over it or of an array of char(n), ORDER BY (a char(n) is text, sorted by the source's collation), a function, ||, a cast, a CASE or an aggregate of such a column goes to the source. A * stays on the copy as a whole item of that one select list (SELECT * FROM t WHERE id = 7), and inside a WITH or a subquery in FROM when nothing goes on to read the char(n) column (SELECT count(*) FROM (SELECT * FROM t) s, WITH x AS (SELECT * FROM t) SELECT id FROM x). It goes to the source when the column is then named, when another * hands it to the client, when the row is used whole, when the block with the * has DISTINCT, GROUP BY, ORDER BY or a window, in a set operation, in a subquery used as a value, and in any shape the port does not follow. It also goes there when the statement casts to char(n), takes arguments, or reads a table with a column of a domain, an enum or another type that is not built in. A char(n) column named in the last SELECT of a WITH goes to the source even when returned as it is: the bytes match, but the port would announce it as text, not bpchar(n). Two more places where a table with a char(n) column stands without its padding counting, and the statement stays on the copy: as a later table of a FROM list written with commas (FROM orders, order_line WHERE ol_o_id = o_id), which joins by what its WHERE compares, as JOIN ... ON does; and under the * of EXISTS (SELECT * FROM t WHERE ...) or NOT EXISTS, whose select list PostgreSQL never reads. In both, the char(n) column itself named in the WHERE still sends the statement to the source. A list that mixes JOIN ... ON with commas is not followed and goes to the source, and so does a * in any other subquery (IN, = ANY, a subquery used as a value or compared as a row) and an EXISTS whose subquery has a UNION, INTERSECT or EXCEPT. The rule is by where the column stands, not by what it would give: WHERE code IS NULL answers the same on both sides and goes to the source all the same. Only the tables the statement reads count, so a table without a char(n) column is answered as before, a column of the same name included; when the port cannot tell which tables a statement reads (a function in FROM, LATERAL, a WITH that is not at the start of the statement, a table the copy does not hold), every table counts. Two kinds of column are treated more strictly, because two values PostgreSQL finds equal can be two values on the copy: a bpchar without a length, which keeps the blanks each value was written with, and every text column of a table whose snapshot was taken before DBTrail recorded column types (the next snapshot records them). Beside one of those, DISTINCT and GROUP BY go to the source too. An array of char(n) is treated as a char(n). The snapshot records a domain's name, not what it is made of, so the port cannot tell a domain over char(n) from any other type.
  • A column the copy does not compare as PostgreSQL does. That is a type that is not built in (a domain, an enum, a composite, a range of your own, an extension's type), a built-in type the copy holds as text (inet, cidr, macaddr, json, jsonb, xml, money, a numeric wider than 38 digits, tsvector, tsquery, the geometric types, the ranges, pg_lsn, bit, "char"), bytea and oid. PostgreSQL compares them by value; the copy compares what is written, so WHERE dc = 'a' on a domain over char(4) found no rows where PostgreSQL finds nine. A statement that compares, groups, joins, sorts, aggregates, applies DISTINCT to or passes to a function such a column is not answered by the copy: it goes to the source, or is refused on a server without a forwarding user. The cost is plain: those reports run on the source, at the source's speed, even when the copy would have answered them right. Only showing the column stays on the copy, as a whole item of a plain select list or through its * (SELECT id, doc FROM t WHERE id = 7): both sides write the same value. The port still announces such a column as text. A statement that does not read the column stays on the copy (SELECT id, total FROM t, SELECT count(*) FROM t, a * inside a WITH whose outer query names other columns). An argument declared bpchar is the source's too: it compares without its trailing blanks.
  • A table whose columns changed on the source since its snapshot goes to the source. PostgreSQL does not announce an ALTER TABLE to capture: capture learns a table's new columns only from the next change made to it, and the copy reads the table with the columns of its snapshot until the table's next snapshot records the new ones (a scheduled update finds the change and takes a full read in its place where it may). In that window the copy would answer with rows PostgreSQL does not return: a text column made char(n) compares otherwise, a numeric(10,2) made numeric(10,0) keeps its decimals, a column added is missing from SELECT *. So before the copy answers a statement, the port reads from the source's catalog (pg_class and pg_attribute, never a row of a table), as the account it forwards with, each table by the OID its snapshot recorded: its schema and name there and its columns (name, type, type modifier and position), and compares them with what the snapshot recorded. Any difference in a table the statement reads sends the whole statement to the source (copy_shape_differs in /status), whatever columns it names and however expensive it is there. This is the one case where a heavy statement does not stay on the copy: its answer there would not be a value written a little otherwise, but rows of a table that no longer exists in that form. A statement that reads only tables that did not change stays on the copy. In detail:
    • The source's answer for a table is kept for one second from when it was asked, so a burst of statements asks once: a statement is decided by a read of the catalog asked at most a second before it (or by the read it waited for), so an ALTER TABLE committed more than a second before a statement starts is always seen by it. Of two reads that overlap, the one asked later wins, whichever comes back first.
    • The question uses a short connection of its own, as the forwarding user, about once a second per server while statements arrive. It takes one of the port's connections to its sources while it lasts, as a forwarded statement does, so the port's bound on them holds for it too. One question is asked at a time for a set of tables; every statement that needs it waits for its answer, and stops waiting when its own statement_timeout or a cancel request ends it.
    • A name without a schema is checked in every schema the copy holds it in: a change of public.t also sends an unqualified read of t to the source when the search_path points at other.t.
    • A table dropped on the source, dropped and created again (another OID), or renamed or moved to another schema counts as changed. Names are compared as PostgreSQL holds them, exactly: a table created as "MixedCase" is found as itself.
    • When the source cannot be asked, the copy answers as it would without the check, with a NOTICE that names the tables and the cause: DBTrail could not check whether <table> changed on your PostgreSQL (<cause>; DBTrail's log has the details). This was answered from the copy as of its snapshot. The cause is one of: your PostgreSQL did not answer within 2 seconds; the port could not connect to your PostgreSQL; your PostgreSQL refused the question (SQLSTATE <code>); the port could not read your PostgreSQL's answer; every connection of the port to your PostgreSQL stayed taken. The router's log has the error itself, at warn level once a minute per server. The failure is kept for two seconds, so a source that is down is not asked by every statement.
    • A table whose snapshot does not record its shape (one last read whole before 0.108.0, which an update from captured changes carries forward as it was) cannot be compared: the copy answers it the same way, with the NOTICE The copy's snapshot of <table> does not record its shape, so it cannot be compared with your PostgreSQL's; a full read records it. An upgrade does not send such tables to the source.
    • Both are counted in /status under copy_shape_unchecked, by why (source_not_asked, no_shape_recorded), apart from the reasons: the statement is counted under the reason it was routed by (answers_the_same, heavy_on_copy, capture_gate and so on). The notice is sent only once the copy's answer is the client's: a statement the copy fails, which the source then answers, gets none.
    • On a server that hides tables or columns, which sends nothing to its source, a statement that reads a changed table is refused with 55000 until the table's next snapshot (counted as refused, under copy_shape_differs).
    • A prepared statement described on the copy before the change and run after it gets what PostgreSQL gives one: 0A000 cached plan must not change result type when its columns changed, after which drivers prepare it again. One described while its table differs is described by the source; each of its executions is checked again, so once the table's next snapshot records its columns the copy answers it.
    • What this does not see: a rewrite that keeps every column's type. ALTER TABLE t ALTER COLUMN n TYPE int USING n + 1 on an int column changes the values and no column, so the shape is the snapshot's, and the copy goes on answering the old values until the table's next full read. A scheduled update does not notice it either. After such a statement, take a new snapshot of the table.
  • A text column under a nondeterministic collation (an ICU collation created with deterministic = false, one that ignores case or accents) follows the same rule: PostgreSQL finds 'ab' and 'AB' equal, groups them as one and sorts them by the collation, the copy compares bytes. A statement that compares, groups, joins, sorts, aggregates, applies DISTINCT to or passes to a function such a column goes to the source, or is refused without a forwarding user; showing it stays on the copy. The snapshot records each column's collation, and the port also reads it from the source's catalog (pg_attribute and pg_collation, never a row of a table) as the account it forwards with, at most once a minute: the source's answer is the one that counts, so a column changed with ALTER ... COLLATE, which keeps its type, is seen without a new snapshot. When the source cannot be asked (it does not answer within two seconds; asked again 30 seconds later), the snapshot's answer stands. A snapshot taken before this version does not record collations: then, while the source cannot be asked, every text column of it is taken for nondeterministic, so a statement that compares, groups or sorts its text goes to the source, or is refused on a server that answers from the copy alone, until the table's next full read records the collation (an update of the snapshot from captured changes keeps what the last full read recorded). A COLLATE written in the statement goes to the source. A database's default collation is always deterministic in PostgreSQL, so it needs nothing of this. For a char(n) column, the type is the one the last snapshot recorded: a column changed from text to char(n) on the source is treated as char(n) from the next snapshot on. When the copy's list of columns cannot be read at all (a copy with more columns than one statement returns on this port), no statement that reads a table is answered by the copy, and the log says so once a minute.
  • A session TimeZone other than UTC, which the harness has not measured.
  • What the copy cannot run, before the client is told anything: a table the copy does not hold, a statement the copy refuses (a reserved word of its own dialect, a value it does not read, such as NaN in a numeric or 24:00:00), a copy that is behind the server's lag limit. A result over the port's row or size cap is still refused, as before: the source would send it whole, past the caps. A column of a numeric declared without precision, which the copy writes with 18 decimals, is sent to the source too.
  • Not a copy that is busy. A statement headed for the copy that finds every worker of the copy taking a statement, and the line for one full or its wait over (--max-wait), is refused with 53000 and a message that says so (the copy is busy (copy_wait_timeout): ...). It is not sent to the source: the port is there to keep heavy reads off your PostgreSQL, and a busy copy is when there are many of them. Run the statement again in a moment; if it happens often, give the copy more workers (--workers, PG_ROUTER_WORKERS in the compose .env) or a longer wait. The connection stays usable, a transaction block is not touched (its statements are the source's), and a prepared statement is tried on the copy again at its next execution. What the source answers anyway still goes there: a statement its plan finds cheap, one the screen sends there. The same holds when the copy is too busy to list its columns, which the screen reads every 10 seconds per connection: the source's plan decides, and what it would send to the copy is refused. With no --max-wait (the default) a statement waits for its turn as long as its client stays connected, and the line holds 4096, more than --max-connections lets connect: so the refusal is in practice what --max-wait sets. A statement that is not short (one worker is kept for short ones) waits for its turn among the others first, then for a worker, which it waits for only behind short statements; each of the two waits is bounded by --max-wait.
  • What is not a query: EXPLAIN, cursors and savepoints outside a block, VALUES, TABLE. A statement that writes is refused (25006). SHOW TABLES and DESCRIBE, the copy's own, stay on the copy.

Of what the copy can answer, only what is expensive on the source goes to the copy. The copy has no index: a read by a primary key takes a millisecond on PostgreSQL, and on the copy it reads the whole table, behind every other statement waiting for a worker (measured: 15 seconds for one row of a table of 2 million). So before a statement the copy can answer goes there, the port asks the source for its plan, with EXPLAIN (FORMAT JSON) on the forwarding user's connection (the statement itself does not run), and sends it to the copy only when:

  • the Total Cost at the top of the plan is 50,000 or more (--cost-threshold, BINTRAIL_PG_ROUTER_COST_THRESHOLD), or
  • the plan has a sequential scan (a Seq Scan node, at any depth: in a join, a subquery, a WITH) estimated at 1,000,000 rows or more (--scan-rows, BINTRAIL_PG_ROUTER_SCAN_ROWS), whatever its cost. A scan run by parallel workers counts the rows of all of them.

Anything else is answered by the source (cheap_plan in /status). 0 turns one rule off; both cannot be 0.

An expensive statement the copy could not return is answered by the source too (result_over_row_cap in /status). The copy returns at most --sql-port-max-rows rows for one statement (200,000 by default: a report of 100,000 rows is not unusual) and refuses a larger result, it does not cut it. A wide result is held to 1,000,000 cells (rows times columns), never under 10,000 rows, which is what any width had before: what an answer takes in the router's memory while it is read and sent follows its cells (about 160 bytes each beside its text, measured) and its text, held up to four times at once, so one answer takes up to about 400 MB, counted in the router's memory sum ("Whether its memory fits the machine"). Its text is also held to 64 MB. A result past any of these is refused with 54000 and counted in /status under result_too_large, as rows, cells, bytes or cell_length (one cell longer than a cell may be). The plan rule below keeps 10,000 rows (or the row cap, when you set it lower): a statement it sent to the source before the cap went to 200,000 still goes there. So when the plan says an expensive statement returns more than 10,000 rows, the port does not try it on the copy, where a wide result could be refused for its cells or its bytes: your PostgreSQL answers it, and sends every row. The plan's estimate is used for one kind of statement, the one where it can be trusted: one table read alone, whole or by an index, with nothing left to check row by row (no Filter in the plan), under a LIMIT or a sort at most (SELECT * FROM orders, SELECT * FROM orders WHERE id > 5000 ORDER BY id). A LIMIT of 10,000 or less (or of the row cap, when lower), written as a number, keeps the statement on the copy. A prepared statement with parameters (LIMIT $1, WHERE id > $1) is never sent to the source for its size: its plan is asked for once, without its values, PostgreSQL then estimates by fixed guesses (a LIMIT $1 is taken to return a tenth of the rows), and the port does not take a guess for the size of a result. It is tried on the copy, as before. For anything else (a filter no index serves, a join, an aggregate, GROUP BY, DISTINCT, a window, a UNION, a partitioned table) the estimate is a guess, so the statement is tried on the copy as before, and one that does return more rows than the cap still gets the copy's error (54000, "the result has more than N rows"). A statement that the source answers this way runs there in full: it is the read of a whole table or a wide index range that the client asked for, and it loads the source as it would without the port. In the compose .env they are PG_ROUTER_COST_THRESHOLD and PG_ROUTER_SCAN_ROWS. The defaults come from a TPC-C source of 97 million rows on PostgreSQL 16: reads by a primary key cost 1 to 12, an order's lines by an index 12, the stock level join 712, a count(*) of one warehouse's orders by an index 15,059, and max(ts) of a heartbeat table 4,202 with a sequential scan of 201,680 rows; of 14 analytics reports, two cost 177 and 699 on PostgreSQL (a table of 2,000 rows, an index range) and stay there, and the other twelve cost 98,367 to 13,351,258, several with sequential scans of 2.4 to 61 million rows.

A statement whose joins would not fit on the copy is not run there. The copy's engine picks the order of a statement's joins with no statistics of its columns, and for some reports it picks one whose intermediate result is far larger than any of its tables: on the CH-benCHmark's Q5 it joined the stock table (20 million rows) with the filtered orders on the warehouse alone, which has 200 values, and gave no answer after three and a half minutes, after which the source answered. In the order written, Q5 answers in 7.5 seconds. So, on a connection with a forwarding user, the copy reads its own plan of the statement before running it (in milliseconds) and estimates each join's output from the source's count of distinct values of the joined columns (pg_stats.n_distinct). The engine's own row estimates fall far short over a table read with its recent changes (fresh mode) or with rows deleted since its snapshot (stock, 20 million rows, estimated at 844,417), so the check takes those back to the table's rows first. A join estimated at more than 100 times its larger input and at more than 3 billion rows (a cross product: more than 10 billion rows) has the statement planned again in the order written; it runs in that order when that plan has no such join, and when it has one too, the copy does not run it at all and the source answers it at once (join_too_big in /status). The counts are read from the source as the forwarding user, on a connection of the port's own and in the background, never inside a client's statement: once every 10 minutes for the server, not for each statement, whether or not routing by plan is on. A read that fails or finds none is said once in the log (a WARNING per server and cause) and tried again after 1 minute, then 2, 4, 8 and every 10; counts are used for up to an hour after the last good read. Only the counts of the tables a statement reads are given to the copy, and a statement that reads one table once, or that the source's plan reads one table with, is not checked: it cannot join two inputs. Without counts (no forwarding user, the capture account, statistics the forwarding user cannot read, a table never analyzed, a partitioned table, whose partitions hold the counts) the copy runs every statement as before. /status counts what the check did with each statement the copy answered under join_checks: planned (checked, the copy's own order), written_order, no_statistics and could_not_run (the copy's plan could not be had or read, also said once in the log). A prepared statement is checked at each execution, with its values, not when it is described. What the check cannot read it does not count against a statement: a condition that is not one column equal to another, a column name two tables share, a join that returns at most the rows of one side. On the 22 CH-benCHmark reports, read through the copy's views with and without recent changes, it changes two: Q5 runs in the order written, and Q21, which runs out of memory in both orders, goes to the source. What it does not catch is an order that keeps every join's output in proportion but builds a hash table from a side the engine thinks small: Q9 over fresh-mode views (order_line joined with stock first) is neither flagged nor changed by the check.

The filter an OR implies is added beside it. When a statement's WHERE, or the ON of an inner join, holds an OR whose every branch says col = literal or col IN (literals) among its conditions, the copy runs it with col IN (every one of those literals) added in AND, so the table is filtered as it is read. The filter is implied by the OR, so the answer does not change; CH-benCHmark Q19 (ol_w_id IN (...) in each branch) went from 1.07 s to 0.42 s on a copy of 100 warehouses. It is added before the join check, which judges the plan that runs. Anything less plain is left as it is: a branch without that column, the column written two ways, a placeholder, NULL, a subquery, a cast or an expression in place of a literal, literals of two types, numbers against a text column, a select item's alias, NOT IN, <>, and an OR in the select list, a CASE, HAVING or the ON of an outer join. Only the copy's text changes; the source, the client and the audit record keep the statement as written.

A statement that runs out of memory on the copy is tried once more in the order written. When the copy's engine fails a statement with its Out of Memory Error in its own join order, the port runs it again on the copy with its joins in the order written, before it sends it anywhere else. Q9 over fresh-mode views ran out of a 2 GB worker after 21 to 59 seconds in the engine's order, and the source then took 42 seconds more; in the order written the copy answers it in 5.5 to 7.9 seconds. The second run takes the same worker slot as the first, so it adds no load beside it, and it reads the same views, so it does not wait for the recent changes again. Its time comes out of the statement's own: what is left of the copy's time limit and of the port's, and at most half of what is left of the client's statement_timeout, so the source still has the other half if the second run fails too. With less than a second for it, the statement goes to the source as before (copy_refused). It is not run again when the first run already used the order written (the statement asked for it, or the join check chose it, which the port also knows when the kernel stopped the worker), when the error is any other than running out of memory, or when the client cancelled or left. Nothing of the copy's answer is sent to the client before the copy has the whole of it, so there are never rows or a row description already sent when it is run again. When the second run runs out of memory or time too, the statement goes to the source under its own reason, copy_refused_after_written_order; on a connection without a forwarding user the client gets the first run's error, which then says it was run again. When the second run fails with another error, that error is the answer, as if the copy had given it the first time: a result too large is refused as such and not sent to the source. /status counts each outcome under join_checks, on either side: oom_retry_written_order_ok (the copy answered in the order written), _failed, _other_error, and, for a statement not run again, _skipped_forced_order, _skipped_check_chose_written_order and _skipped_no_time. Each outcome is one INFO line in the log with the time of each run. A prepared statement's Describe is not counted (it runs the statement under LIMIT 0). The SQL page is not changed: there an out-of-memory error is the answer, as before.

The port remembers a statement shape that needed the order written. When the second run answers, the port remembers the statement's shape for that server, and the next statements of that shape run on the copy with their joins in the order written from the start, with no first run in the engine's order. Q9 then takes one run of about 6 seconds instead of a failed one of 22 to 34 seconds followed by the retry. A shape is the statement with every value replaced by ? (so the same report with other dates or ids is the same shape), together with the schema and search_path; it is the same key the port uses to remember a statement's side by its plan. A statement the port could only read in part is not remembered. Only a second run that answered teaches the port anything: a second run that failed, a statement not run again, a cancel, a time-out or any other error leaves the memory as it was. The answer does not change, only the plan: the order written turns off the engine's join order optimizer and nothing else. A remembered statement keeps the join check, for the order written alone: one shape covers every value of it, and a value can make it far larger than the one it was learned with, so a join estimated far past its inputs in the order written sends it to the source as join_too_big before it runs, and the shape stays remembered. A remembered statement gets at most half of what is left of the client's statement_timeout on the copy, as the second run does, so the source still has the other half. When it runs out of memory or of time in the order written (the copy's own limit, or that half), the shape is forgotten and the statement goes to the source as copy_refused_after_written_order, without a third run, as when the second run fails. Where there is no source to send it to, the client gets the error: the out of memory one, or 57014 for time. The client's own statement_timeout ending it forgets the shape too, and is answered as always. Any other error is answered as that error, and the shape stays remembered. Each shape is remembered for 24 hours from when it was learned, however often it is used, so the engine's own order is tried again once a day: as the data changes it may fit again, and it is usually the faster one when it does. A new snapshot of the copy does not reset it, because what makes the engine pick the bad order is that it has no statistics of the copy's columns, which a new snapshot does not give it. A server remembers at most 4,096 shapes, after which it forgets them all and learns them again. The memory is per server, shared by all its connections, kept in memory only: a restart of the port forgets it (opening the port again after a password change does not). /status counts it under join_checks, on either side: written_order_remembered for each statement run in the order written from the start, and written_order_forgotten for those of them that ran out of memory or time there. The second is part of the first, not beside it: a statement that was forgotten adds one to both, so the two are not added up as separate runs. A remembered statement whose join check passed adds nothing to planned. The log has one INFO line when a shape is learned and one when it is forgotten, not one per statement.

The port also learns the order written from a slow statement. Running out of memory is not the only sign of a bad join order. Measured on the CH-benCHmark's Q7 over fresh-mode views on a live copy (200 warehouses, 4 threads): in the engine's own join order it flips between two plans, one that answers in about 7 seconds and one that takes a steady 31 to 33 seconds, while in the order written the same statement over the same snapshot answers in 5.7 to 6.6 seconds. The join check does not catch it, since no join of it is estimated past 3 billion rows, and its estimates flag it on one copy and not on another, so which plan a server gets depends on the day. So a statement that answers on the copy in the engine's own order and takes 15 seconds or more marks its shape for a trial. The time counted is the engine's own run, not the wait for a free worker or the building of the copy's views, so a statement that queued behind a report is not taken for a slow plan. A statement that failed, one already run in the order written (a remembered shape, or the join check's choice), one the second run after an out of memory answered, and one the port could only read in part never mark anything. The next statement of a marked shape runs in the order written, as a remembered one does: with the join check of that order, and within half of what is left of the client's statement_timeout where the source can have the rest. If it answers in at most half the time of the slow run, the shape is remembered exactly like one learned from running out of memory: 24 hours from that moment, and forgotten, with the statement sent to the source as copy_refused_after_written_order, if it later runs out of memory or time in the order written. If it answers but is not that much faster, the engine's own order is kept for that shape, and no trial happens again for 24 hours. If it fails in the order written (out of memory, out of time, or a join there too big for the join check), it is not sent to the source: the copy answered it before in its own order, so it runs once more, at once, in that order, within half of what is left of statement_timeout where the source can have the rest, and the engine's own order is kept for 24 hours. That second run is answered like any statement in the copy's own order. When the client's own statement_timeout ends the trial, the client gets 57014 as always, and the engine's own order is kept for 24 hours. A cancel or any other error is answered as itself, and the shape stays marked for its next statement. The comparison is deliberately strict: a shape covers every value of a statement, so a trial measured with one date range can be wrong for another, and the 24 hours correct a wrong verdict. Marks are per server, at most 4,096 of them (apart from the remembered shapes, so neither forgets the other), each lasting 24 hours, in memory only. /status counts them under join_checks: written_order_slow_marked for each statement that marked its shape, written_order_trial for each trial, and, as parts of it, written_order_learned_slow (remembered from then on, so its next statements count as written_order_remembered) and written_order_own_order_kept. The log has one DEBUG line when a shape is marked, with the time it took and the threshold, and one INFO line for each trial's verdict.

The copy does not cache a subplan a statement reads twice. On this port the engine's common_subplan optimizer is off: over a view of the copy it wrote the whole view to disk (the CH-benCHmark's Q17, which reads order_line twice, wrote about 3.3 GB and took 19.8 seconds; with it off, 3.4 seconds, with the same answer). The SQL page is not changed.

What this costs and where it can go wrong:

  • One round trip to the source for each statement the copy could answer, and a connection there for that moment (--max-source-connections), given back as soon as the copy is chosen. A client connection holds one there only while something of its own lives on it, so most statements open it, a login of the forwarding user, as a statement the source answers did already. With every one of them taken, the statement waits for one to be given back, as a statement waits in line for the copy: up to 30 seconds, or its statement_timeout when that is shorter, and it gets 53300 only then. A slot is given back as soon as a statement outside a block has its answer, so with 50 clients over the default 16 the wait is a few milliseconds; only blocks held open longer make it run out. A cancel request ends the wait, and its statement_timeout counts everything the statement did, the wait included. When the plan cannot be asked because the source cannot be reached (down, refusing the forwarding user, its connection lost, or no connection free in that wait), the copy answers the statement, as before routing by plan, with a NOTICE that routing by plan is off for the moment (source_unreachable in /status). A statement that reads a table also gets the notice that its columns could not be compared with the source's (counted under copy_shape_unchecked, see the table whose columns changed, above).
  • A statement shape the source answers is asked about once a minute, not every time, when its answer cannot depend on its values: a connection remembers the verdict on SELECT ... WHERE id = 5 for a minute, by its shape (values blanked) and the session's search_path, and sends WHERE id = 6 the same way without asking. Only where every value is compared with = (a >, a BETWEEN, an IN list or a LIMIT can change the plan with the value, and are asked every time), and only for a plan ten times below both thresholds (a plan near a threshold can cross it for another value). A verdict for the copy is never kept: a table dropped and made again on the source would still be read from the copy's old rows. A plan the source refused, for the moment or for good, is asked about again.
  • A connection does not read a value go back after the source answered it; the copy waits for it. The copy is a second or two behind the source in fresh mode: a counter the source just showed a connection as 37413 could read 37405 on the copy the next moment. So once the source answered a connection about a table, a statement for the copy that reads that table on it first reads where the source's WAL stands, then waits, up to 6 seconds and never past its own statement_timeout, until capture's saved position has reached it (the commit of its last whole transaction, or on a quiet source the position the source's walsender last reported) and the copy's recent changes have been brought up to date after that; then the copy answers. When capture is not moving fast enough to get there in the time left (judged from how far its saved position moved in the last seconds), or the wait runs out, the source answers at once and the copy runs nothing (copy_too_old in /status). Measured on PostgreSQL 16 in fresh mode, the counter written every 20 ms and read 100 times from the source then for the copy on one connection: the copy answered all 100, none went back, and on a quiet source 10 of 10. The source's position is asked in the same write as every statement the source answers, right behind it, so it costs no round trip and no connection when the copy waits later; after an extended batch it is asked once the batch is over. Any row or statement's end the source sends counts, also when an error follows it. When no position of the source after its last answer is known (that read was refused, or the connection to the source was lost), the source answers the statement and the log says so once a minute: no clock of the source is compared with the router's. A table read from its snapshot alone (fast mode, a table with no recent changes) says nothing of how far it reaches, so on such a connection the source answers it. Until a statement has read the server's copy in fresh mode there is nothing to wait on: the copy runs to start its recent changes, and the source answers. This holds for every connection with a forwarding user, routing by plan or not: one that ran a transaction block on the source waits for the copy after its COMMIT too. A connection the source never answered, or answered only with an error, reads the copy without waiting. While a statement waits it holds its own connection to the port and nothing else: no worker of the copy, which has not been asked yet, and no connection to the source.
  • That holds table by table, not for the whole connection. The port keeps, per connection, which tables the source answered it about, and a statement for the copy waits, or goes to the source, only when it reads one of them. A statement that reads other tables is answered by the copy at once, however far behind the copy is. What this means for a reader: two answers on one connection about different tables can be of different moments. An example: SELECT balance FROM accounts WHERE id = 7 is cheap, so the source answers it, as of now; the next statement, SELECT sum(amount) FROM payments, is expensive, reads no table the source answered this connection about, and is answered by the copy, a second or two behind (in fast mode, as old as the last snapshot). A payment committed together with a change of that balance can be in the first answer and not in the second. A value of one table still never goes back: after the source showed accounts, a report that reads accounts waits for the copy as before. To have two tables read at one moment, read them in one statement, or in a transaction block, which the source answers whole.
  • Which tables a statement read is told only when it can be proven; when it cannot, the statement counts as having read every table, and the rule is the connection's again, as before. It is proven in two steps. First its text: one SELECT (a WITH at its start, subqueries, joins and set operations included) whose tables are all named in FROM, calling only functions of PostgreSQL's own that read no table (count, sum, coalesce, now, date_trunc and the like). Then the source itself, in the same write as the statement and right behind it, with one query of its catalog: each name must resolve, under the session's search_path, to a plain permanent table that has no child table, is no partition or child itself, and has no row-level security, and the database must hold none of the things that run a user's code where the text shows none. The tables kept are the ones the source names in that answer. So each of these, answered by the source, marks every table: a view, a temporary or foreign table, a partitioned table or an inheritance parent (reading it reads its children), a partition or an inheritance child (the copy can hold its rows under its parent's name), a table with row-level security, a function in FROM, a function the port does not know to read no table (a function of yours, nextval, query_to_xml), a function written with its schema, TABLE x, LATERAL, ONLY, TABLESAMPLE, FOR UPDATE, a WITH that is not at the start of the statement, a cursor (DECLARE, FETCH), SHOW, VALUES alone, EXPLAIN, several statements in one text, text the port does not read whole (a dollar-quoted string, E'...'), a table name written outside ASCII without quotes, more than 32 tables in one statement, a search_path that names pg_catalog or pg_temp, and any statement at all while the database holds an operator or a cast written in SQL or PL/pgSQL, a domain with a constraint, or a function or aggregate of yours whose name the statement calls or writes after a dot (PostgreSQL calls f(t) for t.f when t has no column f). Past 64 tables a connection stops keeping names and every table is marked. In an extended-protocol batch the tables are confirmed once the batch is over (its Sync): a statement for the copy inside the same batch, before that, is held back. Names are compared without regard to case, and a name the statement for the copy writes without a schema counts for every schema that has a table of that name: the copy matches names that way, so more is held back, never less. Operators and casts an extension wrote in C are taken to read no table of yours.
  • An EXPLAIN the source refuses (a table it does not have, a syntax it does not take) sends the statement to the source, which answers it with its own error (explain_failed in /status). So does a text of more than one statement, which is not asked about at all: EXPLAIN of the first would run the others.
  • The plan's numbers are estimates, as fresh as the source's statistics (ANALYZE), and a sequential scan's rows are the rows it is estimated to return after its filter, not the rows it reads.
  • A prepared statement is asked about once, at its first Describe or Bind, before any argument exists, and keeps that side. One with parameters is asked with EXPLAIN (GENERIC_PLAN, FORMAT JSON), which PostgreSQL 16 and later take. On PostgreSQL 15 a prepared statement with parameters goes to the source, however expensive: that EXPLAIN is refused there. A statement first described in the middle of a batch that already went to the source is sent there for that batch, and asked again the next time.

A server that hides tables or columns sends nothing to its source, not a statement the copy refuses, not a transaction block, not a catalog statement: the rules are applied by the copy's views, and a statement run on the source reads past them, whatever the forwarding user's grants (a view there runs with its owner's rights, as a SECURITY DEFINER function does). Such a server is answered by the copy alone; a rule saved while a block is open on the source fails that block. A statement that uses a char(n) column where its trailing blanks count has no source to go to there, on either kind of server, and is refused (0A000, with the column's name) rather than answered with other rows: select the column and compare it in the client, or give the server a forwarding user. /status says so for the server (forwarding_off), and the log once.

A prepared statement keeps the side it was given once its columns were described: a driver that prepared it once (pgx, JDBC) is not told other columns later. One that the copy refused at its first execution runs on the source from then on.

Which side answered a statement: SHOW dbtrail.router_status

On any connection to the port, this statement says which side answered that connection's last statement and why:

SELECT count(*) FROM orders WHERE now() IS NOT NULL;
SHOW dbtrail.router_status;
           name           |                                     value
--------------------------+--------------------------------------------------------------------------------
 server                   | a9d50e10e73cb3b4
 forwarding               | on
 sql_mode                 | fast
 copy_snapshot            | 2026-11-21T00:42:49Z
 copy_age_seconds         | 1
 last_answer              | source
 last_answer_reason       | veto
 last_answer_reason_means | something in the statement is not known to answer on the copy as on PostgreSQL
 last_answer_error        | no
 counting_since           | 2026-11-21T00:42:50Z
 statements_copy          | 1
 statements_source        | 12
 statements_refused       | 1
 reason_answers_the_same  | 1
 reason_veto              | 9

The rows:

  • server: the id of the server this connection reads.
  • forwarding: on when statements of this connection may go to the source, off when the copy answers alone, which on a server the port serves happens only when it hides tables or columns; forwarding_off_reason then says why.
  • forwarding_account: the account statements are sent with, forwarding user <name> or capture account, read-only, tables of the copy only (with the user DBTrail already connects with); none when there is none.
  • sql_mode: fresh or fast.
  • copy_snapshot and copy_age_seconds: when the server's newest snapshot was taken and how long ago that is, unknown before the first snapshot. In fresh mode an answer also reads the changes captured since, so the age of what a statement read is the last answer's own, below. A server whose copy cannot be read says why in copy_unavailable_reason.
  • last_answer: copy, source, refused, or none before the first statement. last_answer_reason is one of the reasons in the table below, last_answer_reason_means the same in a sentence, and last_answer_error says whether the client got an error for it (yes after copy means the copy could not run it and nobody else could answer).
  • When the copy answered: last_answer_indexed_through (every change capture had recorded up to this instant was in what the statement read) and last_answer_age_seconds (how long before the answer that was, rounded up). For an answer that read a table without its newest changes (fast mode, among others) they are what its snapshot files record, as in /status. Both read unknown, and last_answer_age_unknown_reason says why, for an answer whose snapshot files do not record how far they reach or that read no table.
  • counting_since, statements_copy, statements_source, statements_refused and one reason_<name> per reason: the server's counts since the router started, the same numbers /status serves.

What to know about it:

  • The port answers it itself, always: with or without a forwarding user, before the server has a snapshot, over the simple and the extended protocol (psql, psycopg, pgx, JDBC, prepared or not), inside a transaction block, and in a failed block too, where PostgreSQL answers nothing but ROLLBACK: it is how to read which side failed the block, and the block stays failed.
  • It is never sent to the source and never run on the copy, and it is not an answer: asking twice says the same, and it is in no count. Statements the port answers itself (SET, SHOW of a setting, BEGIN, the catalog's listings, time travel) do not change the last answer either.
  • Send it alone. A message that holds it with other statements (SELECT 1; SHOW dbtrail.router_status in one psql -c) is refused whole (0A000) and nothing in it runs.
  • The name is not a setting: SET, RESET and current_setting of it are refused (42704). The dot in the name is on purpose: PostgreSQL keeps dotted names for extensions, so no setting of its own can have this one.
  • SHOW ROUTER STATUS is refused here with the statement to send, SHOW dbtrail.router_status.
  • The time-travel port of bintrail-pg flashback routes nothing and does not answer it.

The copy's worker for short statements

The copy runs --workers statements at once, and one more kept for short statements. Without it, a short statement waited in the same line as the reports, and with reports of many seconds holding every worker, a sum that takes a second alone took 13 to 31 seconds under 30 connections.

  • The reports do not change. Every statement that is not short runs on --workers workers at most, as many as before this worker was added.
  • Short is told before the statement runs, from the plan your PostgreSQL already gave the port to route it: the plan reads one table and joins nothing. It is not told by the plan's cost: on the copy a report is long for its joins, and a sum over a table of 30 million rows costs about as much on PostgreSQL as the cheapest reports.
  • A short statement takes any free worker: the one kept, or one of --workers no report holds. So the copy can run up to --workers plus 1 statements at once.
  • One table is counted on the safe side, on the plan PostgreSQL gives, not on how the statement is written. Short is a plan with exactly one scan of a table (Seq Scan, Index Scan, Index Only Scan, Bitmap Heap Scan) and only Aggregate, Limit, Sort, Incremental Sort, Gather, Gather Merge, Unique, Group or WindowAgg above it. A plan with a join (a self-join too), a SubPlan or an InitPlan (a subquery PostgreSQL kept apart), a CTE Scan, an Append or a Merge Append (a partitioned table read in more than one partition, a UNION), a Subquery Scan, a function, or any other node is not short. PostgreSQL folds some of those shapes into the query before it plans it: a WITH used once, a subquery in FROM, a partitioned table pruned to one partition, and from PostgreSQL 18 a join of a table to itself on its primary key. When its plan then reads one table alone, the statement is short, and on the copy it is one pass over one table.
  • Not short is also any statement the port has no plan for: routing by plan turned off, a server with no forwarding user, a plan the source refused.
  • Short means one table, not fast. A grouping of a large table into many groups, a count(DISTINCT ...) or a window over it reads one table and counts as short. Several of those at once can take every worker, the extra one included; they still take their turn in order with the reports, so a report is never kept waiting for good. What a short statement is kept from is waiting behind reports that join tables. Nothing is stopped for it: a short statement that turns out long runs to its end.
  • What the extra worker costs. Memory and threads are given to each statement, not shared among the workers: the extra statement has its own --threads and up to its own --sql-memory, so the copy can use one statement's memory more than --workers alone would, and keeps one more worker process warm between statements. Each statement's share of the spill disk (half the free disk, split between the statements that can run at once) is a little smaller. To spend no more than before, give the router one worker less (--workers, PG_ROUTER_WORKERS in the compose .env): the copy then runs as many statements at once as before, one of them kept for short statements, and the reports run one fewer at a time. There is no setting that removes the extra worker.
  • The port's own checks (a SET checked on the copy) and its reads of the copy's columns do not wait among the reports.

/status says how it stands now, in copy_lanes: kept_for_short (1), long_limit (--workers: how many statements that are not short run at once), long_admitted (those that have their turn: running, or about to, waiting for a worker behind short statements only), long_waiting (those that wait for their turn), and refused_wait_timeout and refused_queue_full (the ones refused for want of a turn since the router started, also counted as copy_wait_timeout and copy_queue_full in the reasons). A statement the copy refuses at once as unavailable (a copy that lives only on S3, among others) is answered by the source; after the first such refusal, the next statements of that connection do not wait their turn among the reports to be refused, until the copy answers one.

Whether its memory fits the machine

The router's statements on the copy, the recent changes it keeps for fresh mode, and the memory of DBTrail's history store are each sized on their own, and on a machine they share they can together pass what it has. The router adds them up when it starts and once a minute after, and says the sum in its start-up lines and in /status as memory (which shows the last minute's reading). It changes nothing and never refuses to start.

What it adds up is each part's ceiling, not what it uses now:

  • the statements that can run on the copy at once (--workers plus the one kept for short statements), each at its SQL memory plus the headroom DuckDB takes outside that limit (a quarter of it, at least 256 MiB);
  • what the recent changes may hold, once for each PostgreSQL server listed: each server has its own budget (BINTRAIL_SQL_TAIL_MAX_BYTES, a fifth of the memory the router plans with unless set), and any of them can be switched to fresh mode while the router runs. Not counted with BINTRAIL_SQL_TAILS=off;
  • what each statement's answer may take while it is read and sent (about 400 MB: 1,000,000 cells, and 64 MB of text four times), once per statement that can run at once;
  • the results held for clients that have not read them (256 MiB);
  • the memory DBTrail's history store reserves when it runs on the same machine: the one the compose stack brings, or one on loopback whose host name is this machine's. One on another machine is not asked. One that may be on this machine and does not answer is not counted: when the rest fits, the verdict is then unknown, not fits, until it answers.

With no ceiling of its own the router shares the machine with capture and DBTrail's history store, and the sum is compared with the machine's memory. Past it, under heavy reports, the machine swaps and the kernel stops processes for memory, and it can stop DBTrail's history store. The router then warns, in its start-up lines and in its log (once each time it goes over), with what fits: fewer PG_ROUTER_WORKERS at the same SQL memory, or, when not even one fits, one worker and the SQL memory that fits it. With a ceiling of its own (PG_ROUTER_MEMORY, the container's limit) the statements, recent changes and results are compared with that ceiling first: past it, the router's own statements are the ones stopped, and raising the ceiling is advised only as far as the machine holds it beside the buffer pool. When they fit it, what the router can take (its parts, within the ceiling) plus the history store's memory is still compared with the machine, because a ceiling as big as the machine keeps nothing from running out; the advice then says the PG_ROUTER_MEMORY that fits. PG_ROUTER_MEMORY_SHARE is not a ceiling: nothing enforces it, so with it alone the router compares with the machine as without it (the share still sizes the recent changes' budget). The SQL_MEMORY of the compose .env is also the web interface's and the other SQL port's; --sql-memory sets this service's alone.

While no PostgreSQL server is listed nothing runs on the copy, and nothing is said (verdict is idle).

The factory settings (four workers at 2 GB) can ask for more than a 16 GB machine has with DBTrail's history store at its default memory on it, so the router warns there. A 16 GB machine has about 15.3 GiB to give; with one PostgreSQL server, two workers and a history store of 3 GB fit it, which is how the boards run, and each more server adds its recent changes' budget.

In /status, memory has verdict (fits, over, idle, or unknown with why when the machine's memory or the SQL memory cannot be read), compared_with (machine or own_ceiling), available_bytes, need_bytes, own_ceiling_bytes when there is one, and the parts: slots, statement_bytes (each, headroom included), sql_memory_bytes, servers and tails_bytes (every server's together; or tails_unbounded), results_bytes, index_pool_bytes, index_pool (bundled, this_machine, elsewhere, unread or none) and index_pool_unread. advice says what fits when it is over. The SQL memory and the workers are the ones applied at start.

The port's status

bintrail-console pg-router --status-addr 127.0.0.1:9092 [--status-statements]
curl -s http://127.0.0.1:9092/status

/status is JSON: per server (by its id), how many statements each side answered (copy, source, refused), why (reasons), and per side how many finished, how many got an error and how long they took (answers), and its mode: sql_mode (fresh or fast) and where that comes from, sql_mode_from (environment, saved or default). Every PostgreSQL server is listed with its mode, whether or not a statement reached it yet. The document also says fresh (true when BINTRAIL_SQL_TAILS puts every server in fresh mode) and sql_mode_forced (fresh or fast when that setting decides for every server). How old the data of a server's last answer was is data_as_of (every change capture had recorded up to this instant, a commit time on the source, was in what it read) and data_age_seconds (how long before the answer that was, by this machine's clock), with data_age_max_seconds the worst since the process started. Only an answer the client got counts, never a statement the source answered or one that ended in an error. An answer that read a table without its newest changes (fast mode, among others) is as old as the oldest instant its snapshot files record, the one a lag limit is measured by (see the lag limit above): a minute or more for a snapshot just taken, and, for a table with no change, as old as the update that carried it unchanged. When a file it read records none, the answer has no age: data_age_unknown counts them, so with any the worst is a floor, and data_age_unknown_reason says why the last one has none. On a source with no write since, the age grows though nothing is missing; this machine's clock ahead of the source's makes it larger, and behind it smaller, down to 0. With --status-statements each server also carries statements: a row per statement shape and side, values blanked and table and column names kept. That address asks for no password: whoever reaches it reads the counts, and with --status-statements the names of the tables and columns your clients query. /metrics on the same address is this process's Prometheus metrics.

An address that cannot be opened (something else is listening there) does not stop the router: it prints a WARNING at start-up, writes it to its log, and serves the PostgreSQL port without /status and /metrics. Free the address or set another, then restart the router.

The reasons:

SideReasonWhy
copyanswers_the_sameeverything in it answers on the copy as on PostgreSQL
copycopy_commanda command of the copy's own (SHOW TABLES, DESCRIBE)
copyhidden_rulesthe server hides tables or columns: nothing is sent to its source
copyheavy_on_copyits plan on the source is expensive, so the copy answers it even though the port would otherwise send it to the source for how the copy answers it: the answer may differ from PostgreSQL's (simple protocol only, since 0.140.0)
copycapture_gatethe server forwards with the capture account, and the statement did not pass that account's check, so the copy answered it without asking the source for its plan
sourcecheap_planits plan on the source is under both thresholds: the source answers it, by its indexes
sourceresult_over_row_capits plan on the source is expensive and says it returns more than 10,000 rows (or --sql-port-max-rows, when lower): a result that large may be refused by the copy for its cells or bytes, so it is not tried there
sourceexplain_failedits plan could not be had (the source refused the EXPLAIN, a text of more than one statement): the source answers it, its error included
sourcein_transactionthe client's transaction block
sourcevetoa construct the copy answers differently, or is not known to answer the same
sourcesession_differsa session setting the copy is not known to reproduce (TimeZone)
sourcenot_a_selectEXPLAIN, a cursor, a savepoint, VALUES
sourcecatalog_not_on_copya catalog statement the copy does not answer
sourcetable_not_on_copya table the copy does not hold
sourcecopy_refusedthe copy could not run it
sourcecopy_refused_after_written_orderthe copy ran out of memory for it in its own join order, and again when it ran it once more with its joins in the order written; or, for a statement shape the port remembered as needing the order written, in that order (the shape is then forgotten)
sourcecopy_columns_differa column the copy writes otherwise (a numeric without precision)
sourcecopy_behind_source, copy_age_unknownthe server's lag limit
sourcetable_not_captureda table whose capture lost or dropped changes since its snapshot was read (a table capture skips, a capture ledger that does not say which tables or cannot be read, a lost slot, a snapshot published over a known loss), in fresh and fast mode: the copy holds that table as of its snapshot only. Without a forwarding user, or on a server that hides tables, the copy answers it from that snapshot with a notice that says so
sourcecapture_state_stalecapture has not saved its state for more than a minute while the source wrote past the last position it saved, so its record of the changes it dropped is not current and any table of the copy may miss changes, heavy statements included. Where the statement cannot go to the source (a server that hides tables, source_unreachable, capture_gate, SUMMARIZE) the copy answers it with a notice (see When capture stops saving its state)
sourcecopy_shape_differsa table whose columns on the source are not the ones its snapshot recorded (an ALTER TABLE since, which PostgreSQL does not announce to capture), heavy statements included. On a server that hides tables or columns the statement is refused instead, and counted as refused under this reason
sourcejoin_too_bigthe copy's plan of it has a join estimated far larger than its inputs (from the source's n_distinct), in the copy's own join order and in the order written: the copy did not run it
refusedread_onlynot a read
refusedcopy_queue_fullfor the copy, whose workers were all taken and the line for one full: refused with 53000, not sent to the source; run it again
refusedcopy_wait_timeoutfor the copy, it waited for a worker as long as --max-wait lets it: refused with 53000, not sent to the source; run it again

Here answers_the_same counts the statements the copy answered: the ones it answers as PostgreSQL does and whose plan on the source is expensive.

When capture stops saving its state

Whether a table's copy is current is decided from capture's record of the changes it dropped, which capture saves with its position. A capture that saved its state and then cannot save it again (the index refuses the write, the run fails before its save and starts again) keeps the drops it makes after that in memory only, and the record would still read as current.

So the PostgreSQL port stops trusting the record of a server when both hold:

  • capture's last save is more than a minute old, by the index's own clock (stream_state.last_checkpoint against the index server's time, in one statement). A running capture saves at every checkpoint (every 10 seconds in watch, 5 in bintrail-pg stream) even when the source is quiet, and within a fraction of a second of any change, so a save that old means capture is not saving. A minute is the same bound the port uses for a capture that has saved no state at all.
  • your PostgreSQL's WAL is past the last position capture saved: the port reads pg_current_wal_flush_lsn() (on a standby, pg_last_wal_replay_lsn()) as the server's forwarding user, only once the save is past the minute, and compares positions, never clocks. A quiet source is not past it, so its copy keeps answering. The question has a short connection of its own, at most one per server at a time and one a second, not one of the port's connections to its sources: statements sent there while the server is stale can take all of those, and the question must not wait behind them. If it gets no answer within 2 seconds while the save is still old, a server that was stale stays stale.

While both hold, a statement that reads any table of that server's copy is answered by your PostgreSQL, counted as capture_state_stale, heavy statements included: changes capture did not record can leave rows out of a table, or keep rows your PostgreSQL deleted. Over the simple and the extended protocol alike. Where the statement cannot go to your PostgreSQL (a server that hides tables or columns, a statement routed to the copy as source_unreachable or capture_gate, SUMMARIZE), the copy answers it with a NOTICE that says capture's record is not current and why. When the port cannot ask your PostgreSQL where its WAL stands, the copy answers with a NOTICE that says it could not check. The NOTICE is sent with the copy's answer only: a statement the copy fails, and the source then answers, gets none. Both are counted in /status under capture_state_on_copy (stale, unchecked), and /status shows the reason under capture_state for as long as it lasts. The router logs a WARN when it starts, naming how long ago capture saved and both positions, and an INFO when it ends, naming what ended it.

The state is checked when a statement needs it and when /status is requested, at most once a second per server. With neither, nothing is checked: a capture that stops saving on a router nobody uses is warned about at the first statement or /status request after that.

It ends by itself: once capture saves again, statements go where they went before, prepared ones included.

What to know:

  • The WAL belongs to the whole PostgreSQL cluster. Another database, a vacuum or a checkpoint of the cluster moves it too, so a stalled capture on a cluster where anything writes is distrusted even if the captured tables did not change. That sends more to the source, never less.
  • A capture you stopped makes its last save on the way out, and drops nothing after that. The port cannot tell that stop from a capture that failed to save, nor see a capture run by another process, so while the source writes it sends the server's statements to the source until capture runs again.
  • Not covered: a capture that has not saved a position yet (a first run that has seen no committed transaction), and a row saved by a writer that does not record the sent-through position (bintrail-pg reset, a capture older than 0.132.0). On a busy cluster those cannot be told from a stall, so the port keeps trusting the record there. A capture that never wrote its row at all is the case described in table_not_captured.
  • An index clock that steps back past capture's last save makes that save read as just made, until the clock passes it again.

On this page