Hacker News new | ask | show | jobs
Show HN: Mason – A lightweight Postgres read-replica, built on columnar storage (masondata.ai)
113 points by tagspace 11 days ago
Hi HN! TLDR: we’ve built an open-source drop-in replacement for a postgres read-replica, powered by duckdb’s columnar compute engine. It’s very fast. And it looks like postgres.

So, this started out as: let’s just connect Clickhouse to our postgres dbs and throw our analytics queries at it instead. That will speed everything up. But we quickly found that 1) Clickhouse comes with quite the learning curve (engine optimisation) to make it fast (we needed something we could easily drop in to any customer’s postgres scenario), and 2) we had underestimated how different clickhouse’s SQL syntax was to postgres. Don’t get me wrong: we love Clickhouse (it’s ridiculously fast if you know what queries to expect), it just didn’t work for our ad-hoc postgres workloads.

So we went searching for alternatives that were 1) more plug-and-play and 2) looked a lot more like postgres.

We dismissed a bunch based on desk research alone:

- pg_mooncake (seems to have stalled since data bricks bought them)

- pg_duckdb (seems to offer fast queries, or fresh data, but not both - we needed both)

- materialize/risingwave/readyset (like Clickhouse, they require knowing the query shapes upfront - not ideal for ad-hoc workloads)

- firebolt (license makes it challenging to offer to our customers)

- redshift / alloydb / etc (we wanted something cloud-provider agnostic)

And we shortlisted 3:

- pg_clickhouse (Postgres extension that parses SQL in Postgres and pushes the work down to ClickHouse)

- cedarDB (closed-source, Postgres-compatible analytical database)

- duckdb (open-source, embedded columnar analytics engine with a Postgres-like SQL dialect)

We needed to know how they would perform on real postgres queries, so we took a backlog of 5,410 (hand-written) queries (chosen because they had been slow to execute against postgres) from 159 real postgres databases. We then generated synthetic data (dynamically using the schemas from those 159 databases) to fill 159 local databases so we could run the experiment.

We then spun up the 3 short-listed tools locally, and ran each of the 5,410 queries against both postgres and the 3 tools, and compared the results:

- pg_clickhouse (matched postgres 59.4% of the time, refused 39.9% of the queries and was “wrong” 0.8% of the time).

- cedarDB (matched postgres 88.1% of the time, refused 8% of the queries and was “wrong” 3.9% of the time).

- duckdb (matched postgres 84.1% of the time, refused 14.3% of the queries and was “wrong” 1.6% of the time).

Matched meant they returned exactly the same result as postgres. Refused meant they returned an error message (usually telling you some syntax isn’t recognised). And “wrong” meant they didn’t return the same results as postgres. I appreciate that arguably postgres may be the one that is wrong in some cases - but for our use case, we considered postgres the golden source of truth.

So, both duckdb and cedardb performed pretty well (correctly handled more than 80% of the postgres queries we threw at it), out-of-the box. But we really still wanted to try and cover that long-tail.

We chose duckdb as its open-source license would allow us to easily work on the long tail to get the postgres SQL parity we wanted.

So, Mason (linked above), is what we built, powered by duckdb, which now matches postgres on 96% of our 5,410 queries, plus hundreds of other queries that we added, testing it with Metabase, Grafana, Superset, DBeaver and Trevor.io. For the remaining 4%, it errors with a nice clear message telling you how to rewrite your SQL.

We’d love your feedback on what we’ve built. Useful? How can we make it better?

11 comments

I did something sort of similar which is to rewrite postgres so that I could use it against a single file sqlite DB and run in a browser with WASM. https://github.com/drummonds/go-postgres
Ah nice. What do you use it for?
Cool! DuckDB is awesome

I'm very curious with the use case, why do you need to run analytical queries against the postgres read replica? Why not read the WAL and CDC them elsewhere? Especially if it's adhoc then the (short) delay wouldn't be noticeable.

Also did you tried transpiling SQL if you wanted to match the postgres dialect? I've had great success with duckdb <=> postgres using https://github.com/tobilg/polyglot

Sounds like they saw clickhouse as too operationally cumbersome and too much of a shift for their use cases. They seemed to want to reuse existing sql queries or fragments and just get a performance boost, and then also easy spin up these analytical DBs in customer environments on an ad-hoc basis.
Yeah, exactly. Our customers have lots of postgres dbs, and we needed something plug and play that we can throw the existing (postgres) queries at, without having to rewrite them. Also saves setting up a warehouse each time.

And yeah, it uses CDC via the WAL if you sync via logical replication.

Ah a fleet of customer postgres dbs! Makes sense, thanks for taking the time to explain
Hi! Looks like a fun project. The quick setup is very attractive. Question: I get that you convert from row to column format, but it leaves me curious about the following issues.

1. Data partitioning. OLTP databases tend to partition by primary keys, whereas real-time analytics databases partition by time, and also depend on correct ordering of rows for fast query and good compression. How do you optimize the layout so that the column store achieves optimal performance?

2. Updates to data. For similar reasons updates are very expensive in column storage. ClickHouse (my "home" database) largely operates on immutable data for this reason. How do you handle this?

3. Schema migration. What happens when the upstream schema changes?

These weren't prominent in your docs so I figured it would be best to ask directly.

Hi @hodgesrm. Yeah, good questions. We actually spent quite a bit of time on exactly these topics.

What Mason is optimised for:

- We've purposefully optimised Mason for BI use-cases, rather than dashboard use-cases. i.e. we wanted it to be fast for p95 of all adhoc queries thrown at it, rather than being fast for p99 of a fixed set of queries. Optimising to be fast for dashboards (where you know the shapes to expect) is very different to optimising for humans and agents throwing different queries at it every day. We wanted Mason to be ideal for the latter.

Storing data for optimal performance:

- i'm sure you know this, but just for context for anyone else reading this comment - OLAP (column-based) databases (like Duckdb and Clickhouse) store their data as columns, rather than rows, and each column is split into "chunks" of values (~8k rows per chunk in clickhouse, or ~122k rows per chunk in duckdb) and the primary way to make queries fast is to reduce the number of chunks that need to be processed by the engine to answer any given query.

- we tested storing data in primary-key order, but what we found is that for most production postgres databases, the order in which the rows were inserted into the database aligns very closely with the time column that we usually want to filter on (usually created_at). And duckdb automatically stores min-max values for every column of every chunk, with nothing to declare. So, by storing data in duckdb in the order they're stored in postgres, most time-based filters instantly reduce the number of chunks that need to be processed down to just a few. Making it typically very fast for time-based queries.

- where the above sort order falls down is for pk-based row lookups when the key is random (e.g. UUIDs), which we found are still remarkably common in BI-like query loads (usually you start by doing an aggregate, but then you want to drill down into particular rows). For these tables Mason stores a sorted pk-to-row lookup, and rewrites incoming queries to use it to find the row. This took a single-row lookup on 100M rows from ~13 seconds to ~100ms.

- beyond sort-order, the other way to get more performance out of duckdb is to reduce how much data each chunk takes, so that less is read from disk and more fits in memory. This is where compression comes in, and mason will automatically sample each column, during the first sync, and choose the appropriate compression method for that column (e.g. short or repeated values get dictionary compression, long unique values get ZSTD)

- a 3rd type of query that is remarkably common is aggregating by time (day / week / month / etc.) and doing so for different timezones. We found that a significant amount of the query processing time was spent converting timestamps to the appropriate granularity (especially when the query isn't for UTC). Mason now automatically stores, beside every timestamptz column, a 15-min bucketed version of that column. And Mason rewrites incoming GROUP BY time queries to use that column instead. On a sample of 50M rows, this sped up non-UTC queries by 6-7x (less once joins are involved). The column is written at insert (or update) time, so the read queries never need to pay the cost.

Handling updates:

- most of the production databases we work with have a mix of inserts and updates, so it was important for us that Mason handles update workloads correctly, and keeps up with them.

- our decision (described above) to store data in the order they were inserted into postgres was also driven by this requirement. By storing in that order, it means that inserts can just be appended to the end of our duckdb tables, so staying in-sync with postgres is not a processing-heavy operation.

- for updates in duckdb, the expensive part is usually finding the row (and chunks) to update. For tables with random keys, Mason uses the pk-to-row lookup (described above) to find the rows to update, rather than scanning the whole key column, which keeps the steady trickle of updates fast. Large batches of changes are grouped together and applied every few seconds.

- the one part that is harder to keep up-to-date is the pk-to-row lookup itself. We don't write to it on every insert. Instead, rows added since it was last built are read directly from the end of the table, and the lookup is rebuilt in the background once those new rows pass 1% of the table. So lookups and updates are never delayed waiting for it.

- updates do leave dead rows behind in duckdb, so Mason also watches each table and compacts it in the background when enough space is wasted, without interrupting the main flow.

Schema migration:

- we don't currently do anything clever here. When a postgres table is changed, Mason will automatically resync the new table in full. The previous synced data keeps serving until the new data is swapped in.

Have you considered other data sources? The idea is solid, I design Enterprise data warehouses for a living and with AI I have been wondering what's going to be next. Redshift/Snowflake, etc., have their pros but they don't come with predefined ingestion and access control.

Another question, how do you scale duckdb to multi user reads? I guess for you it's 1 file behind a node service? A typical data warehouse could have 1,000 concurrent users on a Monday morning.

And any thoughts on temporary access tokens for odbc? A la https://medium.com/@shashwat_singh/hashicorp-vaults-dynamic-.... This is because I would rather not give any real password to AI agents.

hey kfk. Yeah, we've definitely been thinking about the potential for other datasources. E.g. we already have use-cases internally where being able to ingest from clickhouse, SQS and S3 would be big wins. Do you have particular sources in mind?

Great question about scalability. Mason right now has really been built for the BI use case, where you have lots of sporadic adhoc queries. It does this really well by dedicating every CPU to every query as it comes in, so it responds as quickly as possible. But, internally we also deal with lots of customer-facing analytics usecases, which is more like the case you describe: 1,000 concurrent users accessing a dashboard concurrently. For that case, the easiest thing to do is to simply give your machine more CPU and RAM (that will get to surprisingly far), but then beyond that we'd need to allow scaling the Mason readers horizontally. Definitely something we're going to look into.

ODBC is an interesting use-case. Not something we come across alot. Can i ask what your use-cases are there?

Outside of the dashboard and team features stuff what does this add over just DuckDB + ADBC connected to postgres?

Is pglite and the node stuff even necessary here?

Good question. The majority of the work was two things:

1. the replication logic that keeps duckdb in sync with your postgres (like you'd expect from a read replica)

2. the query rewriter that takes incoming postgres queries and turns them into queries that run fast on duckdb (we've spent a lot of time making sure that most queries are answered in a few 100 milliseconds, even on 10+M rows).

So, I guess the main differences are:

- with ADBC the load still hits your postgres (which is what we wanted to avoid)

- with ADBC you're not guaranteed to get the same answer as postgres (we want confidence that our queries will answer the same, not faster but different)

- you'd have to build your own ETL (if you want to avoid the load on your postgres)

Does that make sense?

Sounds cool. so basically you created a PostgreSQL compatible layer on columnar db so any software on top it is "mostly" indifferent ?
Exactly. Any tool that can talk to postgres can talk to it.
This is really good! We are an avid user of ClickHouse and this is awesome work.
Can replicated tables live on s3/parquet only, as in did you try so?
Haven't tried it to be honest. Currently very lightweight and just syncs directly to the disk where you run it.

But duckdb supports both S3 and parquet so would likely be easy to support.

What's the usecase, if you don't mind me asking?

I guess the advantage is lower storage costs, but the read latency would take a hit (which would definitely affect query speeds). Would be interesting to try.

this seems to be promising with clickhouse great work !keep t rolling !
Very cool.
There are too many software projects with this name.
I have too many friends with this name
There are too many software projects…