Query Optimization

6 posts

netflix4 min readCurated summary

Stop Answering the Same Question Twice: Interval-Aware Caching for Druid at Netflix Scale

Netflix’s Druid deployment now exceeds 10 trillion rows and can ingest 15 million events per second, but repetitive dashboard queries became a scaling problem. Its new experimental caching layer handles rolling time windows by reusing settled historical results and querying Druid only for recent, changing data. Netflix accepts up to five seconds of additional staleness in exchange for substantially lower query load. ## The Scaling Problem - A dashboard with 26 charts can issue 64 queries per load. - Viewed by 30 people and refreshed every 10 seconds, that becomes roughly 192 queries per second. - Druid’s full-result cache misses whenever a rolling time interval changes. - Druid avoids caching realtime segments to preserve result correctness and determinism. - Per-segment caching reduces historical scans but still requires brokers to gather and merge results for every request. - Adding hardware to handle this redundant workload would be prohibitively expensive. ## Caching Only the Unsettled Data - In a three-hour query, most data is already stable; only the newest minutes are likely to change. - The cache stores previously returned historical portions and sends Druid only the uncached interval. - This approach is designed for time-grouped queries such as timeseries and groupBy queries. ## Deliberate Staleness - The cache can make the newest data up to five seconds stale. - This is acceptable because dashboards typically refresh every 10–30 seconds. - Netflix’s pipeline already has up to roughly five seconds of latency at P90. - Many queries also intentionally end at `now-1m` or `now-5s` to avoid unstable, newly arriving data. ## Exponential TTLs - Cache lifetimes increase with the age of each data point because older data is less likely to change. - Data under two minutes old has a minimum TTL of five seconds. - After that, TTL doubles for each additional minute: - 10 seconds at two minutes old - 20 seconds at three minutes - 40 seconds at four minutes - TTLs are capped at one hour. - Fresh data is refreshed frequently to account for late-arriving events, while older data remains cached longer. ## Time-Based Bucketing - A single cache entry per query and interval would still miss whenever a rolling window shifted. - Netflix instead uses a map-of-maps: - The outer key is a hash of the query excluding its time interval. - Inner keys represent timestamps bucketed by query granularity or at least one minute. - Big-endian timestamp encoding preserves chronological order for efficient range scans. - A three-hour query at one-minute granularity becomes 180 independently cached buckets. - When the window moves, most buckets can be reused and only the newly exposed range must be fetched. ## Router-Integrated Cache Service - The cache currently operates as an external service behind the Druid Router. - Cacheable requests are intercepted transparently: - Fully cached requests are answered directly. - Partially cached requests are narrowed to the missing interval and sent to Druid. - Metadata queries and queries without time-based grouping bypass the cache. - The proxy can be enabled or disabled without changing clients. - Netflix views this as an interim design while exploring deeper integration with Druid. ## Query Identification and Lookup - Incoming queries are parsed to extract their interval, granularity, and structure. - A SHA-256 hash is generated from the query’s logical contents, including datasource, filters, aggregations, and relevant context properties, while excluding the time interval. - The cache looks for buckets within the requested range. - Lookup requires cached buckets to be contiguous from the beginning of the requested interval; the provided article text ends while explaining the handling of expired or missing buckets. Netflix’s approach is best suited to frequently repeated rolling-window dashboards where a small, slightly stale tail is acceptable. Segmenting results by time and assigning age-based TTLs allows the system to preserve freshness where it matters while eliminating most redundant Druid work.

Read original(opens in new tab)
kakaoOriginal article

12 Reasons to Upgrade to MongoDB (opens in new tab)

MongoDB 8.0 marks a significant shift in the database's evolution, moving away from simple feature expansion to prioritize architectural stability and substantial performance gains. By addressing historical criticisms regarding write latency and query overhead, this release establishes a robust foundation for enterprise-scale applications requiring high throughput and long-term reliability. ### Extended Support and Release Strategy * MongoDB 8.0 is designated for five years of support (until October 2029), offering a stable "LTS-like" window that reduces the resource burden of frequent major upgrades. * The "Rapid Release" policy, previously exclusive to MongoDB Atlas, now extends to on-premise environments, allowing self-managed users to access minor release features and improvements more quickly. * This policy change provides DBAs with greater strategic flexibility to choose between prioritizing stability or adopting new features. ### Optimized "Majority" Write Concern * The criteria for "majority" write acknowledgment has shifted from `lastApplied` (when data is written to the data file) to `lastWritten` (when the entry is recorded in the `oplog.rs` collection). * This change bypasses the wait time for secondary nodes to physically apply changes to their storage engines, resulting in a 30–47% improvement in write throughput. * While this improves speed, applications that read from secondaries immediately after a write may need to implement Causally Consistent Sessions to ensure they see the most recent data. ### Efficient Bulk Operations * A new database-level `bulkWrite` command allows for operations across multiple collections within a single request, reducing network round-trip costs. * The system now groups multiple document inserts (up to a default of 500) into a single oplog entry instead of creating individual entries for every document. * This grouping aligns the oplog process with the WiredTiger storage engine’s internal batching, significantly reducing replication lag and improving overall write efficiency. ### High-Speed Indexing with Express Plan * MongoDB 8.0 introduces the "Express Plan" to optimize high-frequency, simple queries by bypassing the traditional multi-stage query optimizer. * Queries are eligible for this fast-track execution if they are point queries on the `_id` field or equality searches on fields with unique indexes (or queries using `limit: 1`). * By skipping the overhead of query parsing, normalization, and plan stage construction, the Express Plan maximizes CPU efficiency for the most common database interaction patterns. For organizations managing large-scale production environments, MongoDB 8.0 is a highly recommended upgrade. The combination of a five-year support lifecycle and fundamental improvements to replication and query execution makes it the most performant and operationally sound version of the database to date.

tossOriginal article

Legacy Settlement Modernization: From the (opens in new tab)

Toss Payments recently overhauled its 20-year-old legacy settlement system to overcome deep-seated technical debt and prepare for massive transaction growth. By shifting from monolithic SQL queries and aggregated data to a granular, object-oriented architecture, the team significantly improved system maintainability, traceability, and batch processing performance. The transition focused on breaking down complex dependencies and ensuring that every transaction is verifiable and reproducible. ### Replacing Monolithic SQL with Object-Oriented Logic * The legacy system relied on a "giant common query" filled with nested `DECODE`, `CASE WHEN`, and complex joins, making it nearly impossible to identify the impact of small changes. * The team applied a "Divide and Conquer" strategy, splitting the massive query into distinct domains and refined sub-functions. * Business logic was moved from the database layer into Kotlin-based objects (e.g., `SettlementFeeCalculator`), making business rules explicit and easier to test. * This modular approach allowed for "Incremental Migration," where specific features (like exchange rate conversions) could be upgraded to the new system independently. ### Improving Traceability through Granular Data Modeling * The old system stored data in an aggregated state (Sum), which prevented developers from tracing errors back to specific transactions or reusing data for different reporting needs. * The new architecture manages data at the minimum transaction unit (1:1), ensuring that every settlement result corresponds to a specific transaction. * "Setting Snapshots" were introduced to store the exact contract conditions (fee rates, VAT status) at the time of calculation, allowing the system to reconstruct the context of past settlements. * A state-based processing model was implemented to enable selective retries for failed transactions, significantly reducing recovery time compared to the previous "all-or-nothing" transaction approach. ### Optimizing High-Resolution Data and Query Performance * Managing data at the transaction level led to an explosion in data volume, necessitating specialized database strategies. * The team implemented date-based Range Partitioning and composite indexing on settlement dates to maintain high query speeds despite the increased scale. * To balance write performance and read needs, they created "Query-specific tables" that offload the processing burden from the main batch system. * Complex administrative queries were delegated to a separate high-performance data serving platform, maintaining a clean separation between core settlement logic and flexible data analysis. ### Resolving Batch Performance and I/O Bottlenecks * The legacy batch system struggled with long processing times that scaled poorly with transaction growth due to heavy I/O and single-threaded processing. * I/O was minimized by caching merchant contract information in memory at the start of a batch step, eliminating millions of redundant database lookups. * The team optimized the `ItemProcessor` in Spring Batch by implementing bulk lookups (using a Wrapper structure) to handle multiple records at once rather than querying the database for every individual item. This modernization demonstrates that scaling a financial system requires moving beyond "convenient" aggregations toward a granular, state-driven architecture. By decoupling business logic from the database and prioritizing data traceability, Toss Payments has built a foundation capable of handling the next generation of transaction volumes.

datadog3 min readCurated summary

Husky: Efficient compaction at Datadog scale

Husky is a distributed event store built on object storage for observability workloads reaching trillions of events per day. Because data is written continuously, rarely updated, and queried both recently and historically, its storage layer must minimize object-store fetches while still supporting high query parallelism. The central design challenge is choosing a compaction and layout strategy that keeps fragments manageable without sacrificing query speed. ## Husky’s Query Execution Model - Ingested events are grouped into files called **fragments** and stored in systems such as Amazon S3, Google Cloud Storage, or Azure Blob Storage. - Metadata for each fragment is stored separately in FoundationDB. - For each query: - Metadata is scanned to identify relevant fragments. - Fragments are distributed among query workers. - Workers scan their assigned data. - Results are merged. - Query cost depends mainly on: - The number of fragments fetched from object storage. - The number of events scanned within those fragments. - Husky therefore focuses on: - Reducing the total number of files through efficient compaction. - Organizing data so queries scan as few irrelevant events as possible. ## The Compaction “Goldilocks” Problem - Compaction combines many small fragments into a larger fragment containing the same data. - FoundationDB transactions atomically replace the old fragments with the compacted one, ensuring queries see a consistent state either before or after compaction. - Ingestion writers buffer events per tenant to avoid producing extremely small files, but they flush periodically to keep newly ingested data queryable quickly. - These flushed fragments may contain only a few thousand events, making queries inefficient when they must fetch thousands of objects and metadata records. ## Balancing Fragment Size Husky must find a fragment size that balances several competing concerns: - **Object storage and metadata overhead** - Fewer, larger fragments reduce the number of fetches and metadata entries. - **Compaction cost** - Larger or more aggressively reorganized fragments require more CPU and more object-storage GET and PUT operations. - **Query parallelism** - Smaller fragments allow more workers to operate concurrently. - Larger fragments reduce distribution overhead but can limit parallelism for large analytical queries. - **Scan efficiency** - Query workers use vectorized execution, which is most effective when scanning sufficiently large batches of rows. - **Data locality and compression** - Compaction can place events with similar timestamps or tags near one another. - This improves compression and allows queries to skip irrelevant data, but requires additional processing and query-pattern analysis. Fragments that are too small create excessive fetch and scheduling overhead. Fragments that are too large reduce parallelism and can make broad queries slower. The goal is a “just right” size suited to typical query patterns. ## Storage Layout and Query Selectivity - Husky organizes events along both: - The time dimension. - Spatial dimensions such as tags. - Keeping commonly queried events close together reduces the amount of data that must be scanned. - Similar data also compresses more effectively. - Achieving this layout increases compaction work, creating a tradeoff between lower query cost and lower maintenance cost. ## Scalable Compaction - Husky’s storage system depends on compaction being efficient enough to run continuously at very large scale. - The design must account not only for the final fragment size, but also for the CPU and object-storage costs required to produce it. - Atomic metadata updates ensure that compaction can occur without exposing partial results or inconsistent table states. Husky’s approach treats compaction as a core part of query performance rather than simple file maintenance. A practical design must tune fragment sizes, merge frequency, and data layout together to minimize total system cost while preserving fast access to both recent events and large historical datasets.

Read original(opens in new tab)
figma2 min readCurated summary

The Search for Speed in Figma | Figma Blog

Figma’s search investigation revealed that OpenSearch itself was responsible for less than 30% of total search latency. The larger costs came from query construction and especially permission checks before and after searches. By measuring the correct end-to-end metrics, Figma identified misleading monitoring data and established a foundation for improving search performance at scale. ## Diagnosing the Latency Gap - Figma migrated from an older Elasticsearch version to AWS-managed OpenSearch, a fork created after Elasticsearch’s 2021 license change. - OpenSearch reported an average search time of roughly **8 ms**, while Figma’s API showed: - About **150 ms average latency** - **200–400 ms** latency at the 99th percentile - Minimum latency above **40 ms** - Search performance also varied significantly depending on traffic levels, with peak periods much slower than weekends. - Additional instrumentation showed that substantial time was spent both before and after the OpenSearch request. ## Understanding OpenSearch’s Metrics - OpenSearch distributes a query through a coordinator node to worker nodes, typically sending one request per index shard. - It then gathers, sorts, and fetches results during the query and fetch phases. - The reported 8 ms metric measured only the average time for individual shard queries—not the total time required to coordinate hundreds of shard requests. - Figma’s queries could involve as many as **500 shard-level requests**, many of which ran in parallel but not all. - OpenSearch did not provide built-in metrics or logs for overall query duration. - Figma instead extracted the `took` value from each search response, producing a backend latency measure that aligned more closely with application-level timing. ## Permission Processing as the Main Bottleneck - Less than 30% of total query API time was spent waiting for OpenSearch. - Pre-processing: - Retrieved information about files the user could access. - Built an OpenSearch filter intended to exclude inaccessible files. - Post-processing: - Performed additional permission checks on every returned file. - Was especially slow and consumed more time than the search itself. - The investigation demonstrated that optimizing the search engine alone would not solve Figma’s overall latency problem. Figma’s experience highlights the importance of measuring end-to-end request latency rather than relying on subsystem metrics. Accurate coordinator-level and application-level instrumentation is essential, particularly when distributed searches involve many shards and expensive authorization work.

Read original(opens in new tab)
figma3 min readCurated summary

Postmortem: Service disruption on January 21-22, 2020 | Figma Blog

Figma’s January 21–22, 2020 outages were caused by separate database failures that compounded one another. A long-running query triggered the first incident and created a vacuuming backlog; the next day, PostgreSQL 9 produced a severely mis-planned query after database statistics changed, while aggressive autovacuuming increased write and lock pressure. Upgrading to PostgreSQL 11 restored stability and addressed both the query-planning and autovacuum performance issues. ## Incident Timeline ### January 21: Long-Running Query - Automated alerts reported elevated error rates at 6:11 AM PST. - Engineers found an expensive, long-running database query driving CPU usage. - Canceling the query at 6:54 AM restored normal performance. - The terminated query left behind a backlog of data requiring vacuuming. ### January 22: Database Saturation - Increased write IOPS and lock contention appeared, despite database CPU being below normal. - Queued API requests eventually made Figma unavailable to some users. - Engineers canceled nonessential queries and increased allocated IOPS, providing only temporary relief. - Performance deteriorated again in the afternoon. - Restarting the database temporarily disabled a suspected background process. - Figma performed an emergency upgrade from PostgreSQL 9 to PostgreSQL 11. - The service returned online at 8:15 PM, with metrics back to normal. ## Aggressive Autovacuuming - The vacuuming backlog crossed the threshold for PostgreSQL’s more aggressive transaction-ID wraparound protection. - This mode generated substantial locking and write activity, particularly in the PostgreSQL version Figma was using. - Canceling autovacuum operations on large tables temporarily improved metrics, but the operations resumed. - Fully suppressing the aggressive behavior required changing `autovacuum_freeze_max_age` and rebooting the database. - Autovacuum was a significant contributor, but disabling it did not eliminate all performance problems. ## PostgreSQL Query Planner Failure - A complex query repeatedly appeared in lock-contention reports. - PostgreSQL estimated that the query would return more than 20 million rows, while the actual result contained only three. - The incorrect plan used full table scans instead of expected indexes. - It also wrote large amounts of data to temporary buffers, matching the observed increases in write IOPS and temporary-byte metrics. - The issue was likely caused by inaccurate statistics or a PostgreSQL planner defect or limitation following a routine statistics change. ## Upgrade and Preventive Measures - PostgreSQL 11 generated a substantially better plan for the problematic query. - Newer PostgreSQL versions improve autovacuum performance and query planning. - PostgreSQL 10+ also provides more advanced performance-analysis tools through Amazon RDS. - Figma had already tested the PostgreSQL 11 upgrade in staging and prepared a detailed production rollout plan, allowing the emergency upgrade to succeed safely. - The company planned to improve monitoring for expensive queries and impose stricter limits on query execution time. Figma concluded that upgrading PostgreSQL, improving query monitoring, and enforcing tighter runtime limits were necessary to prevent similar database-driven outages.

Read original(opens in new tab)