PostgreSQL Connector
A StrataBI Platform Module
Powered by Shaleio
module id postgresql_connector · requires StrataBI · one of the data-source connectors
Read-only SQL against PostgreSQL for StrataBI tiles. A tile sends one query and its parameters; one Lambda function in your own AWS account, <name_prefix>-postgresql_connector-query, runs it against your database and writes the rows to your own S3 as the tile's result. Values are bound by the driver, each query has a time budget and is cancelled on the server at its deadline, results are typed, and the database sign-in stays in your Secrets Manager. It is made for PostgreSQL on Amazon RDS, Aurora PostgreSQL or your own servers. It has run in Shaleio's own AWS test account against Aurora PostgreSQL 16 inside a VPC, from a StrataBI dashboard, but not yet against plain Amazon RDS; Tested lists what has run.
The connector reads results two ways:
- The traditional path, psycopg (PostgreSQL's standard Python driver), is the stable path.
- The optimized path, a native Rust reader, needs production validation: it is tested value for value against the traditional path, but not yet in production environments.
The connector uses the traditional path unless an administrator turns on the optimized path with the install setting native_reader = on. The optimized path is for teams that want its speed and accept that it needs production validation: see The optimized path, with its benchmarks.
tile (SQL + inputs) → query Lambda → your PostgreSQL (read-only user, read-only session)
│
└→ typed Parquet in your S3 → the tileThis page covers dashboard tiles. Using the connector from StrataLake depends on StrataLake changes that are still in development.
Before installing
1. A read-only database user
The connector is read-only because its database user is. Create one that can read what dashboards should see and nothing else (run as an administrator, with your own database and schemas):
CREATE ROLE stratabi_reader LOGIN PASSWORD '<generated>';
ALTER ROLE stratabi_reader SET default_transaction_read_only = on;
GRANT CONNECT ON DATABASE analytics TO stratabi_reader;
GRANT USAGE ON SCHEMA sales TO stratabi_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA sales TO stratabi_reader;
ALTER DEFAULT PRIVILEGES IN SCHEMA sales GRANT SELECT ON TABLES TO stratabi_reader;Give it no INSERT, UPDATE, DELETE or TRUNCATE, no sequence USAGE, no superuser or rds_superuser, and no access to extensions that reach out (dblink, postgres_fdw, the lo_* file functions). The connector also refuses writes itself (below), but the user is the control.
2. The sign-in: a secret, or a StrataAPI Manager credential
Each connection signs in with exactly one of the two. Both, or neither, is refused at install.
An AWS Secrets Manager secret (secret_arn) with the user's sign-in. Only username and password are required; an RDS-managed secret already has them:
{"username": "stratabi_reader", "password": "...", "host": "<database host>",
"port": 5432, "dbname": "analytics"}The install settings db_host, db_port and db_name take precedence over the secret's host, port and dbname. The function's role may read this secret, and the secrets of any extra connections, and no other. The password never appears in the function's environment, its logs or its answers. A secret encrypted with a customer-managed KMS key needs secret_kms_key_arn; the role then decrypts through Secrets Manager only.
A StrataAPI Manager credential (strataapi_credential). In StrataAPI Manager, an administrator adds a credential with provider postgresql and the read-only user's username and password, as a service account (recommended), and binds it to postgresql_connector. Install with the credential's name and db_host (and db_name): the credential holds only the sign-in.
- Binding is what grants the read; adding a credential needs no change to the install. The function's role may read only credentials bound to
postgresql_connector, active and in their current version, never another module's. - The connector keeps the credential for one invocation only, so revoking or unbinding it in StrataAPI Manager stops the next query. The tile then shows StrataAPI Manager's own sentence, for example that the credential was revoked.
- Another provider's credential, or a token or an API key, is refused.
- A personal credential works, as StrataAPI Manager allows it, but everyone who can see dashboards built on this connector then sees what that person can see in the database, whatever their own access there. Use a service account with only the access these dashboards need.
StrataAPI Manager must be installed in the same deployment.
3. The network
| Where the database is | What to set |
|---|---|
| Reachable over the internet (a public endpoint, a managed service) | Nothing: the function runs outside a VPC, and TLS is required. |
| Inside a VPC | subnet_ids (private subnets that can reach the database) and security_group_ids (one that the database's security group admits on its port). |
A function inside a VPC also needs to reach S3 (for results), Secrets Manager and Lambda (for StrataBI's status writer) from those subnets: through a NAT gateway, or through VPC endpoints (an S3 gateway endpoint, and interface endpoints for Secrets Manager and Lambda). With a StrataAPI Manager credential, the function also reads StrataAPI Manager's registry in DynamoDB: add a DynamoDB gateway endpoint too. No KMS endpoint is needed.
TLS is always on. sslmode is require (encrypted) by default. verify-full also checks the server's certificate and host name; it needs the RDS certificate bundle added to the package when it is built.
Install
Install StrataBI first: the function uses its AWS SDK for pandas layer to write Parquet.
stratactl install postgresql_connectorThe installer asks for the sign-in (secret_arn or strataapi_credential) and db_host. Both start blank, and an install with no connection stops at its check: "Install at least one connection".
| Setting | Default | |
|---|---|---|
secret_arn or strataapi_credential | One of the two | The secret's ARN, or a StrataAPI Manager credential's name (which needs db_host). |
db_host, db_port, db_name | The secret's, 5432, the secret's or postgres | |
sslmode | require | Or verify-full. |
subnet_ids, security_group_ids | None | Both, or neither. |
sync_timeout_seconds | 25 | A sync query's budget when the call carries none of its own. |
memory_mb | 10,240 | The function's memory, 128–10,240 MB. |
max_query_seconds | 900 | The async timeout: the longest any query runs. You may lower it; see Timing. |
max_rows, max_result_mb | 0, 0 (no limit) | Per result. A positive value cuts the result there, and the result says so. |
result_layout | auto | How a large result is written: single, prefix (parts plus a manifest), or auto. |
native_reader | off | off: the traditional path, psycopg. on: the optimized path (below). |
max_scan_mb | 0 (off) | Refuse a query whose EXPLAIN estimate reads more than this. |
allowed_schemas | All the user can read | |
dashboard_tiles | On | Turning it off also removes its permissions. |
secret_kms_key_arn | None |
More connections (another database, another secret) go in a tfvars map, connections. Tiles use the install's default connection.
From a tile
{"id": "revenue_by_region", "title": "Revenue by region",
"exec": {"type": "lambda", "module_id": "postgresql_connector", "lambda_index": 0},
"query": {"sql": ["SELECT region, sum(total) AS revenue",
"FROM sales.orders",
"WHERE ordered_at >= :since AND region = ANY(:regions)",
"GROUP BY region ORDER BY revenue DESC"],
"params": {"since": "since_date", "regions": "region_picker"}},
"block": {"type": "table"}}- Placeholders are
:name, mapped to dashboard inputs inquery.params. Values are bound by the driver, never written into the SQL text. A text value is at most 4,000 characters, a list at most 1,000 items, and a query at most 100 values. - A list input binds as a PostgreSQL array: write
= ANY(:ids), notIN :ids.::casts are fine. ?is not a placeholder in a tile, so thejsonboperators?,?|and?&cannot be used; usejsonb_exists(col, :key)and the functions like it.- A tile runs async by default; add
"sync": truetoexecfor a quick query (Timing).
What it does on the database
Every query goes through these, in order:
- One read-only statement. The SQL is parsed as PostgreSQL. Only a SELECT, or a set operation of them, with or without CTEs, may run: nothing that writes, defines, loads, calls out or runs a command, no table functions, no schema-qualified function calls, and no row locks (
FOR UPDATE,FOR SHARE). This check explains a refusal early; it is not the control. - Allowed schemas, from
allowed_schemas. - Values bound by the driver.
- A read-only session:
default_transaction_read_only = on. - The read-only database user, which is what makes the connection read-only.
- Limits: the time budget,
max_rowsandmax_result_mb, andmax_scan_mbif set.
Each query opens one connection, with no pooling between calls, then sets statement_timeout (the time left plus 1 s), the read-only session, idle_in_transaction_session_timeout and TimeZone = UTC. Rows are read through a server-side cursor, in batches. The session's application_name is stratabi-postgresql_connector-tile, so its queries show in pg_stat_activity.
Each query writes one audit line to the function's log: who asked (and whether StrataBI verified it), a SHA-256 fingerprint of the SQL, the tables read, how many values, the connection, the outcome and the database's error code, rows, bytes and times. Never the SQL text, the values, the rows or a secret.
Results
The result is a typed Parquet file at the key StrataBI gives, in your deployment's bucket (or CSV, for a tile that asks for it).
| PostgreSQL | In the result |
|---|---|
smallint, integer, bigint, oid | 64-bit integer |
real, double precision | 64-bit float |
numeric | Decimal, with the column's declared precision and scale (up to 38) |
boolean | Boolean |
date | Date |
timestamp | Timestamp, without a time zone |
timestamptz | Timestamp in UTC |
time | Time of day |
interval | Duration |
bytea | Binary |
json, jsonb, arrays | JSON text |
uuid, money, timetz, the text, network and xml types | Text |
A column whose values don't fit its type arrives as text. A result cut at max_rows or max_result_mb is marked as cut, never silently short, and the tile says so.
Timing
- Async, the default: the query may run up to
max_query_seconds(900 s by default), or the tile's deadline if it setsexec.timeout_seconds. - Sync (
"sync": true): 25 s by default, or the tile'sexec.timeout_seconds, at most 120 s. See Execution types.
A tenth of the budget (0.5–3 s) is kept back to cancel, write and report. At the deadline the connector sends PostgreSQL's cancel request and closes the connection, so the query stops on the server too; the database's statement_timeout is a backstop. The tile then says, for example:
The query did not finish within its 25 s budget and was cancelled. Narrow it (filters, fewer columns or rows) or run it as a background tile.
Lambda now allows a function up to 1,800 s, but the install accepts at most 900 s for now: the OpenTofu AWS provider still refuses a longer Lambda timeout. Past 15 minutes, a workload needs S3 caching or a module's own async logic (see Data-source connectors).
One attempt per query
Lambda never retries a connector query: automatic retries are off for the function, and that is not a setting. A query runs once, and a late status from an old attempt cannot overwrite a newer run's.
- If Lambda stops the function itself during an async query (at its 15-minute limit, out of memory, or failing to start), StrataBI's status writer closes the tile as
TIMEOUTorFAILED, unless the tile has been run again since. The function's role may invoke the status writer and no other function. - An async query that waits in Lambda's queue for more than 15 minutes is dropped and reported to StrataBI's status writer, which closes the tile.
Errors
The tile shows a fixed sentence for each kind of failure. The database's own error text never leaves the function; the audit line keeps its error code.
| Kind | What the tile says |
|---|---|
| Invalid | The database could not run the query as written. Check the SQL and its parameters. |
| Refused | Only one read-only query (a SELECT) can run through this connector. (Followed by the check that failed when it adds something: row locks, more than one statement, or the allowed schemas.) |
| Parameters | A query parameter is missing or is not a plain value. |
| Credentials | The database did not accept the connector's sign-in. An administrator should check the connection's secret. |
| Denied | The database refused this query for the connector's database user. |
| Not found | The query names a table, view or column the database does not have, or the connector's database user cannot see. |
| Timeout | The query did not finish within its N s budget and was cancelled. Narrow it (filters, fewer columns or rows) or run it as a background tile. |
| Limit | The query would read more than this connector allows (N), so it was not run. |
| Unavailable | The database could not be reached. An administrator should check the connection's host, port and the connector's network settings. |
| Throttled | The database is busy (too many connections or queries). Try again shortly. |
| Failed | The database reported an error running the query. |
| Reader | The connector's native reader stopped before the end of the result, so no result was saved. An administrator can set native_reader = off to read with the traditional driver. (The optimized path only.) |
The optimized path: what it does and the risks
What it does. With native_reader = on, for a large result (the planner expects 20,000 rows or more) whose columns are all of the types below, strata_native, Shaleio's own Rust code, reads the result instead of psycopg. It speaks PostgreSQL's wire protocol on a second connection (the same user, TLS mode and read-only, UTC, time-limited session) and decodes the binary rows into Arrow.
| Read natively | Always psycopg |
|---|---|
int2, int4, int8, float8, numeric(p, s) with p up to 38 and s ≥ 0, bool, text, varchar, char(n), name, date, timestamp, timestamptz, bytea, uuid | float4, oid, time, timetz, interval, arrays, json, jsonb, money, network types, xml, enums, a numeric without a declared precision or with a negative scale, every other type; a result the planner expects under 20,000 rows |
A statement whose first rows hold a value the native types cannot (a numeric NaN, a date or timestamp outside the years 1 to 9999, infinity) runs again on psycopg, which gives it as it always has.
| Rows | psycopg rows/s | Peak memory | Optimized rows/s | Peak memory | × |
|---|---|---|---|---|---|
| 100,000 | 147k | 33 MB | 226k | 24 MB | 1.5 |
| 1,000,000 | 200k | 139 MB | 455k | 124 MB | 2.3 |
| 10,000,000 | 221k | 221 MB | 368k | 191 MB | 1.7 |
Measured on a laptop against PostgreSQL 16 in Docker: Lambda and a database across a network will be slower on both paths. Traditional and optimized paths has the conditions and every engine.
The risks.
- It is Shaleio's code, not the PostgreSQL project's driver. A defect in it could write a wrong value that looks right. The parity tests below are what stands between such a defect and a dashboard.
- A result cut short is refused: a reader that stops early, or fails on its own thread, fails the run (the Reader sentence above), and the rows read are checked against PostgreSQL's own count before the result is saved.
- Some statements run twice. A value the first rows cannot hold sends the statement to psycopg again: an expensive statement costs twice, and a non-deterministic one (
random(),now(), aLIMITwithoutORDER BY) may give other rows than one run would. - One more connection. The reader opens its own connection, so a large query costs one more connection setup and holds a second backend for a moment.
Tested on PostgreSQL 16 in Docker, against psycopg's rows, every value and type the same, NaN and the sign of zero included: floating-point edge values, every integer width at its limits, numeric(38, s) at its limits, dates and timestamps at the years 1 and 9999 and around both epochs, char(n) padding, control characters, uuid, 6 MB text and bytea, parameters, limits, the deadline and cancel, and a million typical rows compared value by value. No value differs between the two paths.
Not tested yet.
- Production scale. No run on Lambda against RDS or Aurora at size, no hours-long or concurrent load, no network fault or failover in the middle of a result.
- Other references. Parity is only against psycopg, not against PostgreSQL's own tools.
- Other servers and setups. PostgreSQL 12 to 15 and 17, Aurora's and RDS's builds, a database whose encoding is not UTF-8,
sslmode = verify-fullagainst a real CA, RDS Proxy on the reader's connection. - Edge types.
citext, domains over the native types,timestamp(p)with p below 6,varchar(n)andchar(n)in non-default collations, very wide rows (hundreds of columns), and a single value over 64 MB.
Turn it on, or back off. Set native_reader: on (or off) for this module in strata.yaml and run stratactl update postgresql_connector --reconfigure. With off, psycopg reads every result exactly as before and the connector does no native work at all. The results, limits, timeouts and errors are the same either way; only the throughput changes.
Tested
Has run in AWS, in Shaleio's own AWS test account: the function in private subnets with VPC endpoints, against Aurora PostgreSQL 16 with a read-only database user, called by tiles on a StrataBI dashboard:
- an async query whose totals matched the seeded data;
- a sync query;
- a
DELETE, refused; - a sync query that ran past its budget: it timed out and was cancelled on the server, leaving no session or query behind.
Has run in tests, through the function's handler against PostgreSQL 16 in a test container, with stand-ins for the AWS services:
- a tile query writes a typed Parquet result and reports its status;
- parameters are bound, including hostile text and lists;
- the row and size limits cut the result and mark it, and
max_scan_mbrefuses a large scan; - writes are refused, by the statement check and by the read-only session;
- a query at its deadline is cancelled on the server;
- a wrong sign-in, a refused query and a missing table each give their fixed sentence;
- a tile signs in through a StrataAPI Manager credential, and stops once it is revoked.
The shared connector kit has its own unit tests, with stand-ins for StrataAPI Manager's registry and Secrets Manager. The OpenTofu (the function's role, no retries, the status writer as the failure destination) is tested against mocked AWS providers, including IAM decisions that the role cannot read a credential bound to another module, read another module's registry entries, or bind a credential to itself.
Has not run yet: plain Amazon RDS; verify-full against an RDS certificate; the status writer closing an attempt that Lambda stopped; a StrataAPI Manager credential in AWS.
AWS services
AWS Lambda (the query function), AWS Secrets Manager (the sign-in), Amazon S3 (results, in your deployment's bucket), Amazon CloudWatch Logs (the audit lines), and optionally Amazon VPC (subnets, a security group, endpoints), AWS KMS (a customer-managed key on the secret) and Amazon DynamoDB (StrataAPI Manager's registry, with a StrataAPI Manager credential).
Related
Data-source connectors · Execution types · Build a module · Modules
Shaleio