Neki, sharded Postgres, is now available. Learn more
Navigation

Blog|Engineering|Neki

What would Postgres do?

Andres Taylor |

Our users connect their applications to Neki, sharded Postgres, as if they were connecting to regular Postgres. They have expectations about how Postgres will handle their data and respond to their queries. Getting this correct is one of our biggest responsibilities. People build their businesses on the replies from database queries - wrong results are the worst possible outcome. Crashed the server? Not great, but at least we have resilience. Wrong results? All hands on deck!

The nice thing about matching Postgres is that you have a great oracle to test against. Our differential end-to-end tests do not need assertions spelling out the expected result rows. We send the same query to both a vanilla Postgres server and a Neki cluster, and if they don't return the same results or errors, we have a problem. "What Would Postgres Do" is our mantra.

We set up a schema, fill it with data and fire off queries, comparing the results.

This is not enough for us to feel safe though.

One query can be executed in lots of different ways. If the statistics of tables are different, the planner can produce a different plan. How the tables are sharded decides what can be pushed to Postgres. Finally, queries can come over the simple and extended protocols, with different options enabled on the extended protocol. We have to support them all. Let me show you with an actual query example.

The query

SELECT w.name, count(*) AS shipped
FROM order_tracking t
  JOIN warehouses w ON w.country_code = t.country_code
WHERE t.status = 'shipped'
GROUP BY w.name
ORDER BY shipped DESC
LIMIT 5

The two tables:

Show the example data

order_tracking

| tracking_id | user_id | status     | country_code |
|-------------|---------|------------|--------------|
| 1           | 1       | shipped    | US           |
| 2           | 1       | delivered  | US           |
| 3           | 1       | pending    | BR           |
| 4           | 2       | shipped    | DE           |
| 5           | 3       | processing | JP           |
| 6           | 123     | shipped    | US           |
| 7           | 1       | delivered  | BR           |
| 8           | 20      | pending    | NULL         |
| 9           | 2       | pending    | US           |

warehouses

| warehouse_id | name               | country_code |
|--------------|--------------------|--------------|
| 1            | São Paulo Hub      | BR           |
| 2            | Frankfurt Central  | DE           |
| 3            | Tokyo Depot        | JP           |
| 4            | Dallas Fulfillment | US           |

The results of the query would be:

        name        | shipped
--------------------+---------
 Dallas Fulfillment |       2
 Frankfurt Central  |       1
(2 rows)

In Neki, where a join can run depends on how the tables are sharded.

FROM order_tracking t
  JOIN warehouses w ON w.country_code = t.country_code

If both tables are sharded on the join columns, in the same shard group and with the same hash function, we know that two rows that would match in the join live on the same shard.

If however they are sharded on different columns, there's no guarantee that two rows for the US will live on the same shard. The US orders could sit on shard 1 while Dallas Fulfillment sits on shard 2; joining on each shard would lose them.

In our query, order_tracking is sharded on user_id and warehouses on warehouse_id, so the planner can't delegate the join to Postgres.

Grouping is not on the shard key either, so even though we can do some grouping on the shards, we need to do the final grouping on the router. Same logic there - if the grouping includes the shard key, we know all the rows in one group will find themselves in the same shard, so we can delegate the grouping to Postgres.

Planning a query

The Postgres query, and therefore the Neki query planner, has many choices for how to evaluate a query. It can change the order that tables are joined in, it can choose different join algorithms and aggregation algorithms. It can perform the grouping and aggregating before or after the join.

Neki gathers statistics about your tables - how many rows in a table, how many distinct values in a column, numbers like this. These are gathered from each shard; Postgres already collects these for its own planner. The stats system calculates global statistics and these are then used by the Neki planner to estimate how many rows a part of the query returns.

Armed with these estimates, each operator in the query plan gets a cost. If the operator is sending the rows over the wire, we multiply the row count by a constant. If the operator needs to load data into RAM to work on it, we use a different constant. To get the cost of a part of the query plan, the costs of the operators are combined.

By exploring different ways to solve the same thing, and keeping the cheapest option, the planner can produce a plan that is pretty good. There are some situations where the planner can keep more than the cheapest plan - if one of the alternatives returns the data in an ordered form, or if the results are already grouped, the planner might keep it around.

The query planner is like a pure function that takes stats, query and data topology in, and out comes a somewhat optimal query plan. That means that if we change the inputs, we can get a different output. When the query and data topology are fixed but the stats change, then we call each such different output a plan variant.

Testing the plan variants

Checking one plan is not enough though. The planner often has many alternatives to pick from, and they all have to produce the same result. Our differential tests already check that the plan the planner picks for the test data's statistics agrees with Postgres; now we test that the other plan variants agree with each other, and by extension also agree with Postgres.

Since the planner is a pure function, we can vary its inputs and see which plans fall out.

We sweep through different statistics to find the dimensions that are interesting to explore. Once we find the dimensions we want to go through, we start exploring different points in the landscape. When two points produce different plans, we bisect between them, looking for where the switch happens. We use a search budget because the exploration to find plans can run for a really long time. Exploring the TPC-H query #8 found more than 4,000 plan variants, and it was still finding new ones. Some of these plans were very similar, differing only in the order of the tables listed in the FROM clause of the SQL sent to the shards, but there were more than 1,000 genuinely different plans. This is for a single query. This method is not guaranteed to find all plan variations. Since we explore the dimensions from random points, additional runs will increase coverage of the search space.

Neki comes with two different planners - deep and fast. As the names imply, deep does a deeper analysis. It can take longer and use more memory while planning. The alternative, fast, is quicker but much less thorough. They will sometimes produce different plans for the same query/stats input, so we do this exercise with both planners. All plans produced by either planner must return the same results.

To understand the search space, I like to use a visualizer such as a Picasso diagram. The original Picasso diagram changed the selectivity of predicates; we use the same idea but change statistics instead. My monkey brain really needs help like this to understand some things. I understand an image much faster than a table of numbers.

For our query, using the deep planner, the exploration found 18 different execution plans. Here is one diagram showing how changing two dimensions produces 9 different plans. The dimensions that show the most interesting diagram are how many rows in order_tracking and how many rows in warehouses. Click in the colored areas to show the plan that wins for those statistics.

Each color is a plan. Every edge is the planner changing its mind. The nine rows and four warehouses from our test suite are a speck in the bottom left corner; the exploration found seventeen other plans by varying the statistics. For each of these, we store a witness that remembers the stats that produced the plan.

Let me introduce some of the cast in these plans:

  • Sort [TopN] - The TopN operator returns an ordered result and keeps only the top N rows.
  • Sort [Merge] - This operator produces a single sorted output from multiple sorted inputs.
  • Aggregate [Hash/Ordered] - Handles grouping and aggregation using hashing or ordered inputs.
  • Join [Hash/NestedLoop/BatchedNestedLoop/Merge] - An inner join solved using the stated join algorithm.
  • Route [Scatter] - This is the operator that sends a query to one or more shards. The Scatter variant of this operator sends to all shards in a shard group.

Once we've found these plan variants, we execute them. We use a backdoor that lets us set the stats that the planner uses. Everything else is the same source code that is used in production. In this separate run, we compare the Neki plan variants with each other. Same data, same topology, no matter how far off the fake statistics are from the actual numbers - the results must agree.

Plans from sharding differently

Another input to the planner is the sharding data topology. The one we use in our tests is realistic; we carefully selected the shard keys for tables to allow as much push-down as possible.

Changing the topology changes how queries are planned. An example helps here:

FROM orders o
  JOIN users u ON o.user_id = u.user_id

This is an actual example from one of the test data topologies that we use for testing. We use the user_id column on all tables that have it as the shard key. That allows this join to be pushed down to the shard. This alternative is so good that joins executed on the router rarely win. We did such a good job picking shard keys that the router's join code spent most of the test run on the bench, and code that never runs in tests is code we don't trust.

So we also shard badly on purpose. The plan variants test runs a second time on a topology where eligible tables are sharded by their primary keys - the kind of shard key choice we would talk a customer out of. This doesn't change the shard key for users, but orders is now sharded by the order_id column, and the join can't be pushed down anymore. Now the router join variants get their turn.

We have about 9,800 queries in our test workloads across multiple schemas, topologies and data sets. With our plan variants testing, in a recent CI run I looked at, we executed 37,000 plan variants. A lot of the queries are negative tests - queries that we need to fail like Postgres does. Queries that fail during planning don't produce executable variants, though runtime failures can. So it's not a simple ratio of 9,800 queries producing 37,000 plans.

This has caught real bugs, in the planner and in the operators the plans are built from. Here is one.

One bug

We've imported most of the Postgres regression test scripts. Whenever a bug is found in Postgres, tests are added to these files, asserting that Postgres never regresses. Just by importing the tests we found some issues, but this particular query was running without any problems on the test setup.

Here is a simplified version of the query.

WITH values_once AS (
  SELECT user_id, random() AS value
  FROM users
)
SELECT bool_and(a.value = b.value)
FROM values_once a
JOIN values_once b USING (user_id);

Postgres materializes the CTE if it's used more than once, or if the CTE contains a volatile expression. For this query, since random() is a volatile expression and the CTE is used twice, Postgres will materialize the CTE before using it. Assuming users is nonempty and user_id is its primary key, the query should return true.

The plan that Neki produces for the test data does this materialization correctly, but not all plan variants did. Some of them used the nested loop join and calculated random() multiple times. That means that a.value is not guaranteed to be equal to b.value. The final result will be false, instead of what Postgres would return here: true.

Without testing many different plan variants for the same query, we would not have found this issue. If this kind of problem happens to a user, it's even worse than failing on every plan. They might have tested that Neki does the right thing, and then when one of their tables grows, the plan changes and now, maybe without realizing it, they are not getting the correct results.

Every way a client can send a query

The Postgres protocol is a thing of beauty. It is very consistent and understandable, but it's also quite complex, with many configuration options possible. Neki needs to speak the protocol well enough that drivers and frameworks connecting to it still work correctly, even when they use obscure protocol settings.

The Postgres protocol has two main modes. We have the simple protocol and the extended protocol. Within the extended protocol, there are more options - the user can provide parameter types or let the server infer the types. The user can also ask for results in both binary and text formats.

For our example:

SELECT w.name, count(*) AS shipped

We are calculating the count(*) on the Neki router, so we have to encode it ourselves in whatever format the client asked for. In text that is the string "2". In binary it is eight big-endian bytes, and they had better be the same eight bytes Postgres would have sent. The w.name column comes straight from Postgres on the shard, and we ask the shard for it in the format the client wants, so it passes through untouched.

So queries in the suite run in these different modes: simple protocol, extended, extended with the literals pulled out as untyped parameters, and extended with the parameter types declared up front, as some drivers and ORMs do. Simple queries return text results. For parameterized extended queries, a hash of the query selects text, binary, or a per-column mix. Those runs are compared with the same query on Postgres, accounting for unordered results and nondeterministic values where needed.

Beyond the one query

This tooling makes it very easy for us to import more queries. We copy regression tests from the Postgres source code, we use the TPC-H queries, we've been gifted query logs from users (no data, just anonymized queries). All of these are used for testing.

We also use fuzzing. We generate queries and run them against both Postgres and Neki. Since we started this work in March, we've found and fixed more than 70 bugs just with the fuzzer.

We test the protocol in a similar way. Our protocol integration tests send the same messages to both Postgres and Neki and assert that every message is identical, except the three fields that point into Postgres' source code (file, line, and function, the LOCATION: line in psql's verbose output). We skip those fields.

postgres=# \set VERBOSITY verbose
postgres=# select 1/0;
ERROR:  22012: division by zero
LOCATION:  int4div, int.c:846

When Postgres fails, we fail. When Postgres accepts the weird messages, so do we.

What would Postgres do

This is the trick. No need to hand-craft a bunch of test cases when you have the right oracle. We collect queries from wherever we find them, make up some data, and Postgres supplies the expected result to compare against. One query file gets us a plan search, at least eighteen executed plans, four protocol modes and two topologies, and we wrote none of the expected results.

As long as the data is what the tables show, the results should be the same:

        name        | shipped
--------------------+---------
 Dallas Fulfillment |       2
 Frankfurt Central  |       1
(2 rows)

No matter the statistics, the protocol, or the data topology - this is the only acceptable answer. What would Postgres do? That is what Neki does.