Query optimization
It is important to ensure that proper capacity planning of resources is performed to match the expected workload.Host infrastructure
The following are the minimum requirements for the host operating system running any kind of production workload, and should be seen as a starting point for determining the appropriate resources required by a particular workload: PQS host:- Memory: 4 GB
- CPU: 4 cores
- Memory: 8 GB
- CPU: 8 cores
Importance of deliberate PostgreSQL tuning
It is hard to predict what a client’s needs are without knowing their traffic shapes, usage patterns, etc. If PQS data is used heavily in read scenarios with large active ACS, it is advisable to increase RAM available to PostgreSQL to maximise its cache capabilities. The number of CPU cores is strongly correlated with the maximum number of connections. Larger parallelism in query execution will require more simultaneous connections and therefore more CPUs. Please note that if you intend to run OLAP-like queries (reporting-style - lots of aggregations, many joins with large result sets, etc) it will influence the need for additional resources that are typically unnecessary in OLTP-like workloads. In practice, this means that the number of CPUs should match the number of maximum connections to avoid process scheduling in the presence of concurrent long-running queries. By default, the PostgreSQL Docker image is shipped untuned with irrelevant settings (assuming HDD is used on a Raspberry Pi, which is inadequate in most common contemporary scenarios). One needs to actively tune PostgreSQL according to the hardware used to run it. As a starting point, please use online calculator1 to correlate hardware parameters with PostgreSQL startup settings. In Docker container environment pass the configuration parameters as startup arguments, for example:Can PQS run against AWS Aurora?
It has been proven in production environments that PQS works within expected parameters with AWS Aurora (Serverful) as a datastore, provided default settings are in use (for both PQS and Aurora). AWS Aurora Serverless had not been tested yet.Java virtual machine configuration
Appropriate JVM configuration is important to ensure that PQS has enough resources to run efficiently. At minimum the following should be considered for any realistic deployment:PostgreSQL configuration
Users should at least consider the following PostgreSQL configuration items which are relevant to the workloads it will be expected to satisfy (seepostgresql.conf3):
In cases where high performance is required, a Database Administrator will be required to tune PostgreSQL for the intended workload and infrastructure, and iteratively adjust the configuration whilst the system is under simulated workload.
Host environment
PQS requires write access to a local cache directory (configured through--source-ledger-cachedir, default /tmp/scribe) in order to temporarily cache Daml packages. The size of this cache is proportional to the size of all Daml packages observable on the ledger. It is an ephemeral cache - so it does not need to persist beyond a single execution. Containerized environments should configure a disk-based mount, as it is not important for overall performance.
Processing pipeline configuration
If you wish to have more detailed logging for diagnosis, you can adjust the--logger-level parameter to DEBUG or TRACE. However, be aware that this will generate a lot of log output and may negatively impact performance. Therefore it is recommended you de-scope particularly verbose components (such as Netty) to INFO level (see pqs-logging).
Setting the Ledger API queue length is a trade-off between memory usage and performance. The default value is 128, and can be increased to deliver more stable performance, at the cost of requiring additional memory. Note that the buffer will consume memory equal to the size of transactions in the rolling window of the buffer size:
max_connections9 parameters is set to no less than the number of connections requested from all clients of the database.
Query analysis
This section briefly discusses optimizing the PQS database to make the most of the capabilities of PostgreSQL. The topic is broad, and there are many resources available. Refer to the PostgreSQL documentation for more information. PQS makes extensive use of JSONB columns to store ledger data. Familiarity with JSONB is essential to optimize queries. To get an explanation of how the query performs, prefix query text withexplain analyze. This helps verify that a query executes as expected, using the indexes that you expect it to.
Indexing
Indexes are an important tool for improving the performance of queries with JSONB content. Users are expected to create JSONB-based indexes to optimize their model-specific queries, where additional read efficiency justifies the inevitable write-amplification. Simple indexes can be created using the following helper function:| Index Type | Comment |
|---|---|
| Hash | Compact. Useful only for filters that use =. |
| B-tree | Can be used in filters that use <, <=, =, >=, > as well as prefix string comparisons (for example like 'foo%'). B-trees can also speed up order by clauses and can be used to retrieve subexpressions values from the index rather than evaluating the subexpressions (for example when used in a select clause). |
| GIN | Useful for subset operators. |
| BRIN | Efficient for tables where rows are already physically sorted for a particular column. |
Testing
Any of modified settings need to be independently assessed and tuned. Users should establish performance testing and benchmarking environment in order to validate the performance of PQS on a given workload. It should be noted that the following variables are extremely relevant to overall PQS performance characteristics:- Network latency
- Ledger transaction throughput
- Ledger transaction sizes
- Contract data sizes
Payload queries
This page discusses techniques and considerations for optimizing queries that involve payload contents in the Participant Query Store (PQS). It is assumed that these pages have already been consumed as background knowledge:pqs-how-to-query-contracts-and-transactions-using-sqlpqs-references-sql-api
Metadata indexes
PQS data retrieval functions already come indexed for efficient access that involves metadata-level queries (for example, querying for contracts created at particular ledger offset or lookup of a contract by its contract ID). However, most business workflow-level queries need to select data based on contracts’ actual payload contents. Default indexes that come with PQS cannot help with this since efficient querying depends on knowing Daml model’s details. In other words, each application team is responsible for creating and maintaining appropriate indexes to ensure optimal performance to match their data access patterns.Necessary tools
We will be employing PostgreSQL’spsql1 application and EXPLAIN2 SQL command to analyze query plans and rectify potential performance bottlenecks. Please, refer to the references listed at the end of this page for to learn more about these tools.
Daml model
For the purpose of this page, we are utilizing a simple Daml model which represents a register of tokens created by issuers and held by holders. The actual workflow is not relevant for this discussion so it’s not provided in its entirety, however it is beneficial to see how aToken model translates into a matching JSONB payload representation.
Test data setup
To illustrate the ideas, we have ingested a PQS instance from a Daml ledger that resulted in the following data storage footprint with a variety of data distribution characteristics:Payload indexes
Status quo (no custom indexes)
If we take no care to create any custom indexes, we can still query for contracts based on their payload contents, however the performance may be suboptimal. Let’s explore a few examples.Index Scanare in use, however the indexes are of general nature (for example default metadata-level ones)- PostgreSQL could parallelize execution (
Workers Launched: 2) - queries differ in selectivity (
rows=9vsrows=3972), however this was irrelevant for optimal execution since PostgreSQL did not forecast estimates accurately (rows=976) (being orders of magnitude off) - PostgreSQL performs quite a bit of work to be later discarded (
Rows Removed by Filter:)
payload column is a black box to it. It cannot make any assumptions about its contents (with content being a complex non-scalar structure) and therefore cannot maintain any meaningful statistics to help it make sound decisions. As a result, PostgreSQL consumes more-than-necessary quantity of CPU, memory, and I/O resources to produce equivalent amount of output.
Improving performance with a targeted index
When we know our data access patterns, we can create custom indexes to help PostgreSQL optimize its query plans. The query above seems to be able to benefit if thequantity field is indexed. With JSONB columns PostgreSQL allows to create indexes on expressions3 that refer to particular fields from the JSONB document.
- correct custom-tailored index is in use (
Index Scan using __contracts_14_token_quantity_idx) - PostgreSQL estimates the number of rows much more accurately (
rows=14vsrows=9) - no wasted work performed (
Rows Removed by Filteris gone) - no need to parallelize (
Workers Launchedis gone) so PostgreSQL can conserve its resources to serve other workloads
Understanding interplay of multiple indexes
Independent criteria
Let’s assume that we want to query for tokens held by a particular holder and whose quantity is within a certain range. In case condition criteria are independent, PostgreSQL can combine multiple indexes using bitmap operations to further optimize query plans. Let’s see how this works in practice.Heap Blocks: exact=200 vs Heap Blocks: exact=10483 + Rows Removed by Filter: 9132) to produce the same output faster and cheaper (no need to parallelize query processing).
Dependent criteria
However, if condition criteria are dependent, PostgreSQL tends to greatly underestimate the number of rows that will be returned and therefore may choose a suboptimal query plan. This usually happens when 2 attributes are separately indexed (for example, to support querying over each field in its own right by different code paths) although there exists an intrinsic relationship between the attributes. In such a case, simply having indexes defined is only half of the equation. The other half is to ensure that PostgreSQL has access to relevant statistics to make sound decisions. Let’s see how PostgreSQL can be taught to act right in such situations.wallet.holder and wallet.label fields such that wallet.label is derived from wallet.holder. Refer to the example JSONB payload above for the demonstration.
rows=820 and rows=976 to be returned for each index’s data set, however when combined the estimate is rows=4 which is orders of magnitude off from reality (rows=974).
Recognizing this fact and instructing PostgreSQL to collect relevant statistics45 will in turn optimize the query execution plan.
rows=1028 vs rows=974). While this approach might not necessarily result in dramatic query speed-up, it does significantly reduce the chance of PostgreSQL mispredicting and choosing a suboptimal execution plan.
There exist other multi-variate statistics types that PostgreSQL can employ, please refer to the documentation6 to explore if they can help you with your particular data and queries.
Statistics precision
Oftentimes, the default statistics target (100) is not sufficient to capture the data distribution characteristics for your particular case (for instance, your data exhibits a large skew towards a particular numeric spectrum). In such cases, it might be highly efficient to increase the statistics target for particular expressions7 to capture your data’s peculiarities. We can demostrate the benefit of increased statistics precision by examining the real top 10 token quantity values vs the statistics PostgeSQL collects.
Conclusion
To summarize, PostgreSQL has all necessary tools to optimize queries that involve payload contents stored inJSONB columns. However, it is up to the application developers to create, maintain and monitor appropriate indexes and statistics to ensure optimal query performance. This can be achieved by:
- creating custom indexes on expressions that reflect your data access patterns
- ensuring that PostgreSQL has access to relevant statistics to make sound decisions
- creating multi-variate statistics for dependent criteria where appropriate
- increasing statistics target for expressions that require higher precision to capture data distribution nuances
VACUUM ANALYZE runs). Therefore, it is recommended to strike a balance between query performance and maintenance overhead.
Remember that adding an index is not a panacea for all performance woes. The key to fast queries is controlling their selectivity. For a query whose predicate matches 20%+ of the table, a sequential scan is likely to be faster than an index scan. Master the use of EXPLAIN command to identify and eliminate performance bottlenecks.
Don’t underestimate the pragmatism of keeping your Daml models simple and flat. Deeply nested structures are harder to index and query efficiently. Consider denormalizing your Daml model if it helps achieving better query performance for downstream applications.
Footnotes
- https://pgtune.leopard.in.ua/?dbVersion=15&osType=linux&dbType=oltp&cpuNum=8&totalMemory=64&totalMemoryUnit=GB&connectionNum=100&hdType=ssd ↩ ↩2
- https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/AuroraPostgreSQL.Reference.ParameterGroups.html#AuroraPostgreSQL.Reference.Parameters.Instance ↩ ↩2
- https://postgresqlco.nf/ ↩ ↩2
- https://www.postgresql.org/docs/current/runtime-config-autovacuum.html#RUNTIME-CONFIG-AUTOVACUUM ↩ ↩2
- https://www.postgresql.org/docs/current/runtime-config-resource.html#GUC-MAINTENANCE-WORK-MEM ↩ ↩2
- https://www.postgresql.org/docs/current/runtime-config-wal.html#RUNTIME-CONFIG-WAL-CHECKPOINTS ↩ ↩2
- https://www.postgresql.org/docs/current/runtime-config-wal.html#GUC-MAX-WAL-SIZE ↩ ↩2
- https://www.postgresql.org/docs/current/runtime-config-resource.html#RUNTIME-CONFIG-RESOURCE-BACKGROUND-WRITER ↩
- https://postgresqlco.nf/doc/en/param/max_connections/ ↩
- https://www.depesz.com/tag/unexplainable/ ↩
- https://explain.depesz.com/ ↩
- https://www.postgresql.org/docs/current/indexes.html ↩