Why Medplum queries slow down and how to find the cause
When FHIR searches or API calls slow down on a self-hosted Medplum, the cause is usually found by splitting the request's time into five parts: database execution, wait for a PostgreSQL pool connection, cache access, network round trips, and application work inside the Node.js server. Each part points to a different fix, so a team that tunes the database before it knows where the time goes can spend days on the wrong layer. This method applies when latency alerts fire, when clients start timing out, or when users report slowness after a Medplum release or a sharp growth in stored records. Those three triggers usually have different likely causes, so the first step is to record which trigger started the investigation and when it began.
Medplum's server is built on Node.js and TypeScript and uses PostgreSQL as its database and Redis as its cache, so the slow component can sit in any of the three services or in the connections between them. A slow search may be a query plan that no longer fits the data, a request that waits behind other work for a connection from the pool, a Redis call that takes longer than normal, or a network path whose round-trip time has spiked since a infrastructure change. Each of these leaves a different trace. The team should confirm which timing signals its deployment exposes, including server logs, database statistics and load balancer metrics, before it starts changing settings, because a fix made without evidence can hide the symptom and leave the cause in place.
Where a slow request spends its time
A slow Medplum request usually starts at the client and passes through the load balancer and the Medplum server before it reaches the connection pool, PostgreSQL and Redis. Each hand-off can add delay, so check them in order: time spent waiting for a pool connection, time inside a slow query, latency to Redis, and time in application code. The logs from each layer, correlated on the same request, show which segment grew.
Hand-offs between client, Medplum, PostgreSQL and Redis, with the checkpoints for each.
Five causes that account for most slow Medplum requests
Slow Medplum requests usually trace back to a small set of causes: a query that scans instead of using an index, a search index that has not finished absorbing writes, requests queued for database connections, network latency to PostgreSQL or Redis, and application servers that are saturated. Each card names the symptom and the first check, so you can separate these causes before changing any setting.
Slow SQL and missing index use
Symptom: a specific FHIR search type is slow while others are fine, and PostgreSQL time concentrates in a few statements. Start with pg_stat_statements to rank statements by total and mean execution time, then enable auto_explain with a log threshold to capture plans for the slow ones. Check whether the plan uses a sequential scan where you expected an index scan. A plan that changed after a Medplum upgrade or a large data load is a strong lead. Confirm the expected indexes with Medplum's index configuration before adding anything by hand.
GIN pending list effects on search
Symptom: searches on indexed text or array-backed fields are slow during or right after heavy write bursts, then recover on their own. GIN indexes buffer new entries in a pending list, and a search may have to scan that list, so reads can slow while it is large. Compare search latency with write volume over the same window. If the pattern follows bulk imports or Bot-driven writes, consider scheduling those loads and checking whether the pending list cleanup runs as expected on your PostgreSQL version. Confirm the behavior against your index definitions first.
Requests waiting for pool connections
Symptom: latency climbs across all endpoints at once, while PostgreSQL CPU and query times stay flat. The time is spent before a query starts, waiting for a free connection in the application pool. Compare request duration with database query duration in your logs. If the gap grows under load, the pool is too small for the concurrency or long transactions are holding connections. Check active connections against the server's connection limit, and confirm whether a pooler such as PgBouncer sits between the application and PostgreSQL.
RTT spikes to PostgreSQL or Redis
Symptom: short, repeated slow periods where every request gains a fixed delay, often across several endpoints at once. Measure round-trip time from the application hosts to PostgreSQL and Redis during those windows, and compare against normal baseline. Cross-zone placement, a changed network path, or resource contention on a shared host can each add delay. Check whether the application servers and data stores sit in the same network region, and whether Redis calls are issued sequentially in the slow path, since each call multiplies the added delay.
Cache misses and overloaded app servers
Symptom: latency rises with traffic on one or more application instances while others stay quick, or Redis hit rates drop and database load grows in step. Check the Redis hit and miss ratio and eviction count, then compare CPU and event loop lag on each Medplum server. A cold cache after a restart or deployment can send reads straight to PostgreSQL. A single instance running hot points to uneven load balancing or a long-running request. Confirm the Redis memory limit and eviction policy before resizing anything.
Using auto_explain and pg_stat_statements to find slow SQL
The pg_stat_statements extension aggregates execution statistics for normalized SQL statements across all sessions, so it answers the question of which statement consumes the most database time. Start here before you look at individual slow requests, because a statement that runs thousands of times with a small mean time can cost more in total than one rare, very slow query. Medplum's FHIR search layer generates many similar statements, so normalized grouping helps you see the pattern rather than individual parameter values.
- Rank by total time: Sort by total execution time to find the statements that consume the most database capacity overall. This ranking usually points to the workload you should fix first.
- Rank by mean time: Sort by mean time per call to find individually expensive statements, such as a search that scans a large table on each call.
- Read calls and rows together: A high call count with few rows returned suggests many small lookups. A low call count with many rows returned suggests a broad query or a missing filter.
- Reset and compare windows: Reset statistics before a test or change so that you compare clean windows instead of cumulative counts since the last restart.
- Confirm availability: Check that the extension is installed and listed in the shared preload configuration on your instance. Managed PostgreSQL services differ in which extensions they allow, so confirm this with your provider.
Check that the top total-time statement is one your application actually issues, then take its normalized text to the plan capture step.
The auto_explain module writes the execution plan of any statement that runs longer than a threshold to the PostgreSQL server log. It captures the plan that actually ran, including row estimates and actual row counts, which you cannot always reproduce by running EXPLAIN by hand with different parameter values. Set the threshold with care, because logging plans for every statement adds overhead and inflates log volume.
- Set a threshold: Use
auto_explain.log_min_durationto log only statements above a chosen duration. Pick a value that captures your real slow statements without flooding the log. Confirm the right value with your own latency targets. - Enable actual timing selectively: Options such as
auto_explain.log_analyzeandauto_explain.log_timingadd runtime detail but increase overhead. Turn them on for a short investigation window rather than permanently. - Plan the log overhead: Plan logging costs CPU and disk I/O on the database host and can grow the log quickly under load. Measure the effect in a staging environment first.
- Check nested statements: Use
auto_explain.log_nested_statementsonly when you need plans for statements run inside functions, since it multiplies the output. - Load the module: Add
auto_explainto the shared preload libraries and restart PostgreSQL, or confirm that your managed service allows it and how to set it.
After capture, match each logged plan to its normalized statement from pg_stat_statements so you know which request path produced it.
Plans show how PostgreSQL reads each table. A sequential scan reads every row in the table and filters them, which is acceptable for small tables or queries that return a large share of rows. An index scan or index-only scan uses an index to locate matching rows directly. In a slow Medplum search, a sequential scan on a large resource table with a selective filter is a common sign that an index is missing or unused.
- Look for Seq Scan on large tables: A Seq Scan node on a big table with a filter that removes most rows usually means the query is not using an index for that predicate.
- Compare rows estimated and actual: Large gaps between the planner's row estimate and the actual row count often mean stale statistics. Running ANALYZE on the affected table may correct the plan.
- Check the filter and removed rows: The Rows Removed by Filter line shows work done for rows that were discarded. A high count means the index does not cover the predicate.
- Read the total and loop counts: Multiply actual time by loops to see the real cost of nodes inside a nested loop, since per-loop figures understate it.
- Identify index choice: An Index Scan or Bitmap Heap Scan can still be slow if the index returns many rows. Judge the plan by how many rows each step touches, not by the node name alone.
Before you add or change an index, confirm which predicate the slow statement filters on and whether the index matches the search parameter the application sends.
Checking GIN index pending lists during FHIR search
A GIN index can slow some reads and writes for a while after new rows arrive, because PostgreSQL can buffer new index entries in a pending list and merge them into the main index later. This matters for Medplum because its FHIR search depends on indexes over JSONB resource data, and GIN is the index type PostgreSQL commonly uses for JSONB containment and key lookups. When a search that was fast yesterday becomes slow after a burst of writes, a growing pending list is one possible cause to rule in or out. It is not the only one, so check it alongside the other causes in this section before changing anything.
To check the pending list, first identify the GIN indexes on the Medplum database with the pg_indexes view or \di in psql, then read their settings with pg_index and the index options. The fastupdate storage parameter controls whether new entries go through the pending list, and gin_pending_list_limit sets the size at which the list is flushed. The pgstattuple extension can report pending list size for a given index, and the gin_clean_pending_list() function merges pending entries into the main index on demand. Autovacuum also cleans the pending list, so compare the last autovacuum time on the table with the period when searches slowed. Run these checks on a copy or a quiet period first, since cleanup adds I/O.
Before you change fastupdate, gin_pending_list_limit or vacuum thresholds, confirm with the Medplum documentation and your own schema which index types Medplum creates, on which columns, and with which settings, because search indexes can be created or managed by the server and altering them by hand may conflict with upgrades. The PostgreSQL documentation on GIN indexes explains the trade-offs of the pending list in detail. Record the pending list size and search timings before and after any change so you can show whether the change helped.
Step-by-step sequence to isolate the slow component
This sequence moves from one slow request to the specific layer causing it, so the team fixes the component that is actually slow rather than tuning the first thing that looks suspicious. Each step ends with a check that tells you whether to continue or stop.
Capture the slow request and time window
Start by recording one concrete slow request: its method, FHIR resource type, path, approximate timestamp, response time and status code, taken from the load balancer, the client, or the application log. Also note the size of the time window and whether the slowness is constant or intermittent, since a steady slowdown and a burst point to different causes. Confirm you can name a single request and a window of time that contains other slow requests. If you cannot reproduce or find one example, collect more data before moving on, because every later step depends on a specific request.
Trace the request ID across logs
Use the request identifier that the load balancer, the Medplum server and any proxy write into their logs to follow that one request through each tier. Search each log source for the same identifier and line up the timestamps in a single table. Confirm the match when you can see the request enter the load balancer, reach a Medplum server process and produce a database-facing entry, with no gaps large enough to suggest a dropped or retried call. If identifiers are missing from a tier, note that gap as a logging change to make before the next incident.
Compare application time to database time
Split the request's total duration into time spent inside the Medplum server and time spent waiting on PostgreSQL and Redis. If the application logs or traces show query durations, subtract them from the total to estimate the time spent in the application itself, such as JSON serialization, access policy evaluation or Bot execution. Confirm which side holds most of the time. When the database accounts for most of the duration, continue to the pool and connection checks. When the application accounts for most of it, focus on application profiling instead of database tuning.
Check pool wait and connection counts
Look for requests that waited for a free PostgreSQL connection before any query started. Review the pool's wait metrics or logs and compare the number of open connections against the configured pool limit on each application server. Also count total connections across all servers and any connection pooler in front of PostgreSQL, since many servers each holding a full pool can exhaust the database's connection limit. Confirm the check when you can state whether requests queued for a connection during the window and how many connections were in use at peak. A queue at the pool points to sizing or leaked connections, not to a slow query.
Measure Redis and PostgreSQL round-trip time
Measure network round-trip time from the Medplum server to PostgreSQL and to Redis, using a simple probe run from the same host and availability zone, and compare it with the values during a normal period. A short query issued repeatedly is enough for this. Spikes in round-trip time across all queries, not only heavy ones, point to the network path, a failover, an overloaded instance or cross-zone routing. Confirm the step by stating whether round-trip time was flat or spiked during the slow window and whether the spike matched the request timestamps.
Confirm the slow statement with pg_stat_statements and auto_explain
Query pg_stat_statements for the statements with the highest total and mean execution time during the window, and check whether the slow request's queries appear there. Then enable auto_explain for a short, controlled period with a threshold that captures only the slow statements, and read the plans it records. Look for sequential scans on large tables, plan changes after a statistics update, and GIN index entries that are still pending. Confirm the statement when you can name the exact SQL, its plan and the index or condition responsible. Keep the auto_explain threshold and duration limited, since plan logging adds overhead.
Fix the identified component and re-measure
Apply one change that matches the evidence, such as adjusting the pool limit, adding a missing index, changing a query shape, or moving a pending GIN index into its normal state, and record the change with its timestamp. Then repeat the same request, the same time-window measurement and the same statement statistics under similar load. Confirm the fix when the request duration, pool wait or statement mean time returns to the baseline you captured in the first step. If the metric does not move, return to the earlier step that pointed to the wrong layer rather than stacking further changes.
Tracing one request across application and database logs
The goal of tracing is to follow one slow API call from the load balancer into the Medplum server, then into PostgreSQL and Redis, using the same timestamp window and the same identifiers at each hop. Start with a single slow request: take its time, HTTP verb, path and status code from the load balancer access log, then find the matching Medplum server log lines within a few seconds either side. Compare the request duration recorded at the load balancer with the duration the application reports. If the load balancer shows a long total time but the application logs a short handling time, the delay sits before the request reaches Medplum, in connection queuing or the network path. If the application time is long, the next step is to check whether the time was spent waiting for a database connection or executing a query, and whether a Redis call appears in the same window with a long round trip.
Each hop needs a key to join on, and not every deployment captures one by default. Check what your load balancer access log records, such as the client address, target processing time and any request identifier header it adds, and confirm that the Medplum server logs the same request identifier or a request ID it generates. PostgreSQL logs usually do not contain an HTTP request identifier, so you will often correlate by time and by the statement text, using log_min_duration_statement or the slow query output from auto_explain to find statements that ran during the same window. Confirm with your own configuration which fields each log captures before you rely on them, because the names and formats depend on how your deployment was built. If no shared identifier exists, match on the narrowest possible time window, the endpoint path and the database user, and record the gap as a logging change to plan.
OpenTelemetry tracing can link these hops automatically, but it is optional and must be enabled for your deployed version before you depend on it. Confirm in the Medplum self-hosting documentation and your release notes that the server, the database and the Redis client emit spans, and check that a trace identifier appears in the logs so you can search by it. Until that is verified in your environment, treat log correlation by timestamp and identifier as the working method. Test it with a deliberately slow request in a non-production environment before an incident, so the team knows which fields exist and how long a search across the log stores takes.
Which diagnostic tool fits which symptom
This table maps the most common slow-request symptoms to the first diagnostic to run, what it reveals and what it costs to use. Read it by matching the symptom you see to a row, then check the overhead and access column before enabling anything on a production database. The main takeaway is that pool and network measurements should come before index or query changes, because they rule out the most common causes quickly.
| Symptom | First tool | What it shows | Overhead or access requirement |
|---|---|---|---|
| One slow query type | pg_stat_statements | Normalized statements ranked by total and mean execution time, with call counts and buffer usage | Extension must be loaded in PostgreSQL; low overhead; needs a role that can read the view |
| All requests slow | Pool wait and RTT measurements | Time spent waiting for a free pool connection, and round-trip times from app servers to PostgreSQL and Redis | Application and infrastructure metrics access; no database changes required |
| Spikes under load | Pool wait metrics, then pg_stat_statements over the spike window | Whether requests queue for connections during peaks, and which statements dominate when load rises | Metrics retention must cover the spike; pg_stat_statements needs a reset or snapshot plan to compare windows |
| Slow only on search | auto_explain | Execution plans for search statements that exceed a duration threshold, including index use and row estimates | Adds logging per slow statement; set a threshold to limit log volume; requires server configuration access |
| Slow search on GIN-indexed fields | GIN pending list inspection | Whether recent writes sit in the pending list, which slows reads on GIN indexes until they are merged | Read access to index metadata; confirm the index type and pending list settings with your PostgreSQL version |
| Slow only from one region | RTT measurements and request tracing | Latency from that region to the API and to PostgreSQL or Redis, and where time is spent in a single request | Needs log correlation across the load balancer, app servers and database; tracing may require added instrumentation |
| Slow for a single request ID | Request tracing across logs | The sequence of services and timings for one request, from entry point through database and cache calls | Requires consistent request IDs in logs; confirm log retention and access controls before investigating |
Security and access when troubleshooting production data
Slow query investigation touches the same data that clinical users see, and the diagnostic tools that expose query text and timing can leak PHI as easily as the application does. The cards below cover who gets database access, what reaches the logs, and how tuning changes are approved, so that troubleshooting does not create a second, weaker path into patient data.
Least-privilege diagnostic database roles
Create a dedicated PostgreSQL role for diagnostics that can read pg_stat_statements and the statistics views but cannot read clinical tables or change data. Keep the Medplum application role separate from administrative roles, and grant pg_read_all_stats only when the on-call team needs it. Choose the authentication method for these roles according to your policy, since PostgreSQL documents several options, including password, certificate, LDAP and OAuth. Confirm which option your identity team can enforce and review role membership on a schedule.
Redacting PHI from logged parameters
Slow query logs and auto_explain output can record bind parameters, which in a FHIR workload often contain patient identifiers, names or dates of birth inside search values. Decide whether parameter logging is needed at all, and if it is, route logs through a redaction step before they reach shared storage. Test redaction with real query shapes from a non-production copy, because redaction rules that miss one search parameter will leak it silently.
Limiting who reads slow query logs
Treat slow query logs as protected health information when they contain unredacted values, and restrict read access to the engineers who are on call for the database. Check whether your log platform records who searched or exported log entries, and whether those records are retained. Ask the platform team to confirm that log access follows the same approval path as database access, not a looser shared dashboard.
Protecting logs in transit and at rest
Query telemetry moves from the database host to a collector, then to a storage backend, and each hop needs encryption and access control. Confirm that the connection from PostgreSQL and Redis to the collector uses TLS, that log storage is encrypted at rest, and that backups of log stores follow the same retention rules as the data they describe. Document where each copy lives so that a deletion request or incident review can find every one.
Change control for production tuning
Index creation, ALTER SYSTEM changes, and statistics or auto_explain threshold changes can lock tables, increase write cost, or alter plans for every tenant. Require a written change record with the query, the expected effect, the rollback step and an approver who did not make the change. Test index builds on a restored copy first, and schedule changes that take heavy locks outside clinical hours.
Auditing diagnostic sessions
Every interactive session on the production database during an investigation should be attributable to a named person and a ticket. Enable connection logging for the diagnostic role, record who ran EXPLAIN or read statistics views, and keep those records alongside the change record. Ask your security team to confirm which events they need retained and for how long, because that answer determines what the audit trail must capture.
Questions teams ask before troubleshooting Medplum performance
How long does it take to find the cause of slow Medplum queries?
The length depends mostly on whether the slowness reproduces on demand and how much evidence the team already has. A slow path that appears in logs with a known endpoint, a clear time window and a reproducible request is usually faster to isolate than an intermittent slowdown with no timestamps. The work moves through a fixed sequence: confirm where the time is spent (application, pool wait, PostgreSQL or Redis round trip), identify the statements or request paths responsible, then test a change in a non-production copy. Each step can expand if the database lacks statement statistics or if logs cannot be correlated across the application and the database. Ask any partner to state the sequence and the evidence they need before they give a schedule, and to confirm that the schedule covers a verification run after the fix, not only the diagnosis.
Can our own team troubleshoot Medplum query performance internally?
Yes, if the team has someone comfortable with PostgreSQL query plans, connection pooling and distributed log tracing. The core tools are PostgreSQL's own statistics and logging, so the skills gap is usually interpretation rather than access. Internal teams often struggle in three places: separating application time from database time, judging whether a GIN index pending list or a missing index is the real cause, and proving that a change helped under realistic load. An outside team adds most value when the production system is hard to touch, when the root cause has resisted two or more attempts, or when an audit trail of the investigation is needed. Whichever path is chosen, agree in writing who owns the database changes and who signs off on production rollout.
What access and evidence do we need to provide for a performance investigation?
The investigation needs read access to the relevant logs, metrics and database statistics, plus one or more reproducible requests. In practice that means:
- Application logs with request identifiers, timestamps and response times, covering the slow period
- PostgreSQL statistics from
pg_stat_statementsand anyauto_explainoutput the team already collects - Redis and PostgreSQL latency metrics, and connection pool metrics from the application tier
- A recorded example of a slow request, with the endpoint, the query parameters (with any patient data removed), the caller and the time it was sent
- Deployment history, so changes to the application, the database or its settings can be lined up against the slowdown
Access to a non-production environment with a comparable dataset is important, because query plans depend on data volume and distribution. Confirm how any patient data is handled before anything is copied, and how the environment is controlled under your own compliance program.
What does a Medplum performance troubleshooting engagement cost?
Cost is set by the written scope, so there is no standard figure to quote here. The main drivers are how many layers are involved (application, pool, PostgreSQL, Redis, load balancer), how many distinct slow paths need work, whether a reproduction environment must be built, and whether fixes are expected to be implemented or only recommended. Ask for the quote to separate the diagnosis from any remediation, to state what is one-time (the investigation report and fixes) and what recurs (monitoring, retesting after upgrades or data growth), and to list which environments and log sources are included. Your own costs also count: staff time for access reviews, change windows and sign-off. DeployOpen does not publish a price list, so the quote follows from the agreed scope.
Does tuning Medplum queries or PostgreSQL settings require downtime?
Many fixes do not, but some do. Adding an index on a large table can lock writes or consume significant I/O unless it is built with a non-blocking method, and PostgreSQL parameter changes may need a restart depending on the setting. Statistics collection, pool size changes and some application configuration changes can usually be applied in a rolling way across application servers. Before any change, confirm which settings require a restart, how long an index build will take on your data volume, and whether a read replica can absorb the rebuild. Plan changes in a maintenance window only when the database check says a restart or lock is unavoidable, and keep a tested rollback for each change.
When should we upgrade Medplum or PostgreSQL instead of tuning queries?
Consider an upgrade when the cause is a known defect or a platform behavior fixed in a later release, or when the database version is near the end of its support window. Tuning is the better first step when a specific query or request path is responsible and the platform version is current. PostgreSQL's supported versions are 18 (final release November 14, 2030), 17 (to November 8, 2029), 16 (to November 9, 2028), 15 (to November 11, 2027) and 14 (to November 12, 2026). Medplum must be upgraded through each minor version in sequence, and post-deploy data migrations can run for hours or days on large datasets, so an upgrade is a larger project than a query fix. Compare the two paths against the release notes and your support calendar before choosing.
Which parts of a slow request can be traced end to end?
A request can usually be traced from the load balancer or ingress into the Medplum server, then into PostgreSQL and Redis, provided each layer records a shared request identifier and timing. The gaps are typically at the pool boundary, where a request waits for a connection before any query runs, and at Redis calls that look fast in aggregate but stall under contention. Confirm that your logs carry the request identifier through every tier, that clocks are synchronized across hosts, and that you can filter by time window and endpoint. Medplum's optional OpenTelemetry support can help with this, and the upgrade guide and deployment docs describe the components to check for each version.
How DeployOpen scopes and delivers Medplum performance troubleshooting
DeployOpen approaches slow Medplum queries as a fixed-scope investigation: we confirm which requests are slow, collect evidence from PostgreSQL, Redis and application logs, and trace the cause to a specific query, index, pool or network path. Findings are delivered with written fixes, a verification method and handover notes for your own team to run inside infrastructure you control.
How we scope
- Agree in writing which slow endpoints, Medplum server versions and environments the investigation covers.
- Confirm access to PostgreSQL statistics, slow query logs, Redis metrics and application logs before work starts.
- Define the symptoms, time windows and acceptance criteria that mark the problem as resolved.
How we build
- Enable auto_explain and pg_stat_statements carefully, with thresholds and log volume agreed up front.
- Review query plans, GIN index pending list behavior and pool wait patterns against captured request traces.
- Test each proposed fix in a non-production copy of the deployment before any change reaches production.
How we hand over
- Deliver a written findings report that ties each slow path to its measured cause and evidence.
- Document the queries, dashboards and log searches your team needs to reproduce the diagnosis.
- Walk your engineers through the runbook for tracing a request across logs and database timing.
How we support
- Offer a retest of the affected endpoints after fixes are applied, as part of the agreed scope.
- Make ongoing support, upgrades and continuous testing available as a retainer for changing workloads.
- Confirm support terms, response expectations and any further work in a written quote before engaging.

