<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vijay Jayaram on Medium]]></title>
        <description><![CDATA[Stories by Vijay Jayaram on Medium]]></description>
        <link>https://medium.com/@vijay.jayaram?source=rss-2ff3f89e407------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JogI6PbnUqM5AppSQknCOg.jpeg</url>
            <title>Stories by Vijay Jayaram on Medium</title>
            <link>https://medium.com/@vijay.jayaram?source=rss-2ff3f89e407------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:23:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vijay.jayaram/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Under the Hood of Mixpanel’s Infrastructure]]></title>
            <link>https://medium.com/mixpaneleng/under-the-hood-of-mixpanels-infrastructure-0c7682125e9b?source=rss-2ff3f89e407------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c7682125e9b</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Vijay Jayaram]]></dc:creator>
            <pubDate>Tue, 09 Apr 2024 06:44:40 GMT</pubDate>
            <atom:updated>2025-05-14T20:17:45.604Z</atom:updated>
            <content:encoded><![CDATA[<p>Mixpanel’s analysis UI is powered by an in-house database called Arb, which is built for ingesting, storing, and querying trillions of events in real-time. This page covers the core aspects of our design, the pain points it eliminates for users, and how it compares to other systems.</p><figure><img alt="A segmented funnel in Mixpanel, computed dynamically on top of billions of events in real-time." src="https://cdn-images-1.medium.com/max/1024/0*ZmjfVdgn1R1WzXQ8" /></figure><h4><strong>Event-Centric</strong></h4><p>Mixpanel is built for ingesting, storing and querying events. Each event has a name, a timestamp, a unique identifier, a distinct_id that identifies the entity that performed the event, and a JSON blob of properties.</p><pre>{<br>  &quot;event&quot;: &quot;Signed up&quot;,<br>  &quot;properties&quot;: {<br>    &quot;time&quot;: 1618716477000,<br>    &quot;distinct_id&quot;: &quot;alice@mixpanel.com&quot;,<br>    &quot;$insert_id&quot;: &quot;29fc2962–6d9c-455d-95ad-95b84f09b9e4&quot;,<br>    &quot;Referred by&quot;: &quot;Friend&quot;,<br>    &quot;URL&quot;: &quot;mixpanel.com/signup&quot;,<br>  }<br>}</pre><p>Events are a simple and powerful way of collecting and storing data for the following reasons:</p><ul><li>Events map cleanly to real-world actions. When something happens at a point in time to a user, you can track it with all the context you know about that event.</li><li>Events are granular. Any question about user engagement, conversion, or retention can be modeled as an aggregation over a user’s event stream. The event data model makes no assumption about the queries it might receive, so it serves as a flexible foundation to power arbitrary queries. Events can be summarized by any property (to form a metric) or segmented by any property (to drill down into a metric) completely on-the-fly.</li><li>Events are immutable and append-only. When something happens in the real-world, it never “un-happens”. Immutability makes it possible to design an event-native system in a performant and cost-effective way.</li><li>Events are flexible. They can model actions that go beyond user activity: support tickets, pull requests, Slack messages, payments, CDC from a database, etc.</li></ul><p><strong>What this eliminates</strong>: Precomputation, rollups, or indexing.</p><h4><strong>Optimized for Interactive User Joins</strong></h4><p>Mixpanel’s UI is built for interactive exploration of event-based metrics. We must respond to queries within seconds to make data exploration delightful at scale.</p><p>Our query engine employs the usual techniques for CPU performance: columnar storage, dictionary encoding, a query optimizer, and a purpose-built query engine in C/C++.</p><p>We also shard events based on their `distinct_id`, the property that identifies the actor who performed the event and sort by `time`. This combined with our in-memory query engine enables behavioral queries (funnels, flows, retention) to be computed with high parallelism, no shuffling, and no expensive fact-on-fact joins, leading to low query latency.</p><p>Finally, we benefit from cloud economics: 1 CPU for 100 seconds costs the same as 100 CPUs for 1 second, but the latter can respond to queries 100x faster. Multitenancy makes this approach possible at scale and enables fast queries over billions of events.</p><p><strong>What this eliminates</strong>: Data sampling, fact-on-fact joins, and manual refreshing of dashboards.</p><h4><strong>Real-Time</strong></h4><p>Events are available for analysis in Mixpanel within seconds of hitting our ingestion servers. Arb leverages a lambda architecture to collect recent events in a row-oriented format while storing historical events in a time-partitioned columnar format. This enables fast, real-time analysis and efficient historical analysis.</p><p><strong>What this eliminates</strong>: Waiting for periodic ETL jobs or caches to populate.</p><h4><strong>Schema-On-Read</strong></h4><p>Events contain an arbitrary set of JSON properties. The properties associated with a given event type are typically stable, but they might occasionally change when new features are added to the product being tracked. Systems that enforce a schema at collection-time require some sort of schema upgrade for this to happen, which can be time consuming to rollout, especially when collecting events from client devices. That said, schemas are useful to provide features like property autocomplete to the person performing analysis.</p><p>Mixpanel solves both problems with schema-on-read. Events are ingested and stored with arbitrary JSON and we infer schemas in real-time to power the autocomplete menus in our UI. Our schema inference also accounts for recency so that stale schemas naturally age out.</p><p><strong>What this eliminates</strong>: Schema migrations.</p><h4><strong>Star Schema</strong></h4><p>Mixpanel’s <a href="https://docs.mixpanel.com/docs/how-it-works/concepts">data model</a> is fundamentally a star-schema: events are facts and user profiles/lookup tables are dimensions. Events are typically streamed in from client devices and server logs, while dimensional data is periodically loaded from a system of record and provides enrichment to the events for analysis.</p><p>Arb’s query and storage engine can run star-schema joins on the fly. This means events and dimensions can be loaded at any time without any coordination, rather than needing to be joined at ingestion. This query-time approach also enables backfills of events and dimensions to be done retroactively.</p><p><strong>What this eliminates</strong>: Ingestion-time enrichment. Coordination between streaming and batch systems.</p><h4><strong>Idempotent</strong></h4><p>Mixpanel’s ingestion pipeline is idempotent, which means that events that are accidentally sent multiple times will not affect analysis. This simplifies integration of Mixpanel into your own streaming or batch data pipelines as it turns exactly-once ingestion into at-least-once ingestion. Unlike other systems which deduplicate for a short time window at ingestion, we take a <a href="https://engineering.mixpanel.com/petabyte-scale-data-deduplication-mixpanel-engineering-e808c70c99f8">novel query-time approach to deduplication</a>. This enables us to detect duplicates even if they arrive months later.</p><p><strong>What this eliminates</strong>: Keeping state about what you have already sent to Mixpanel.</p><h4><strong>Cloud-Native</strong></h4><p>Mixpanel is a fully managed cloud application, maintained by the Mixpanel team and deployed on Google Cloud. Like other cloud-native databases, it decouples compute from storage, which reduces costs at high-scale.</p><p>Being on Google Cloud also lets us utilize cloud primitives to ship features faster, scale seamlessly when load increases, and leverage enterprise-grade security provided by Google.</p><p><strong>What this eliminates</strong>: Server maintenance, upgrades, and capacity provisioning.</p><h4><strong>Open APIs</strong></h4><p>There are <a href="https://docs.mixpanel.com/docs/quickstart/what-to-track#how-to-track">many ways to integrate</a> with Mixpanel, but all are based on our JSON-over-HTTP APIs. We believe it should be easy to bring data into or out of Mixpanel with whatever tools you already use, whether it’s a CDP, a data pipeline, or a simple cURL.</p><p>This approach allows us to plug into the broader data ecosystem, which makes it easy to both stream real-time event streams into Mixpanel and load from source-of-truth systems like data warehouses. Here is a reference, hybrid architecture for bringing data into Mixpanel, enabled by our APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EJnXJcaabSQG9vt8" /></figure><p><strong>What this eliminates</strong>: Complex integrations and proprietary data formats.</p><h4><strong>Comparison to other systems</strong></h4><p>Mixpanel makes a set of tradeoffs to achieve the above design goals. Here, we compare Mixpanel to other popular database systems to put these tradeoffs in context:</p><ul><li>Mixpanel is not an OLTP system like MySQL, Postgres, or DynamoDB. We do not have support for ACID transactions, indexes, point-lookups or arbitrary SQL. That said, Mixpanel can ingest the change-data-capture events from an OLTP database to provide behavioral analytics.</li><li>Mixpanel is not a data warehouse like Snowflake or BigQuery. Data warehouses provide a relational model and SQL semantics to go with it. They are a great choice as a scalable system of record for all business data that you collect and enable all sorts of queries. However, this generality comes by with poorer performance and ergonomics for ingesting real-time events and answering product analytics questions. Mixpanel can ingest from a data warehouse via <a href="https://docs.mixpanel.com/docs/tracking-methods/data-warehouse">Warehouse Connectors</a>.</li><li>Mixpanel is similar to OLAP systems like Clickhouse, Druid, or Pinot. All are optimized for fast, self-serve analytics on immutable data and support both real-time or batch ingestion. The latter systems are open-source and support a SQL-like dialect. This means they can be plugged into open-source or off-the-shelf collection or visualization tools. However, they require developer time to maintain, are expensive because they do not decouple compute and storage, and can also be slower as they do not benefit from multi-tenancy. Finally, they are slow for the types of user joins that are needed for behavioral analytics. Mixpanel is fully managed, vertically integrated from the UX to the database, and built for user joins.</li></ul><p>Ultimately, Mixpanel specializes in answering questions about user behavior (funnels, flows, retention) on top of large-scale, immutable event streams. We achieve a step function improvement in performance, cost, and ease-of-use by focusing on this use case and provide open APIs to plug into any other tool in the data ecosystem.</p><p>For more technical details about how Mixpanel is built, follow our <a href="https://engineering.mixpanel.com/">engineering blog</a>. If this excites you, <a href="https://mixpanel.com/careers">join us</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c7682125e9b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mixpaneleng/under-the-hood-of-mixpanels-infrastructure-0c7682125e9b">Under the Hood of Mixpanel’s Infrastructure</a> was originally published in <a href="https://medium.com/mixpaneleng">Mixpanel Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power-of-2-Choices in Practice]]></title>
            <link>https://medium.com/mixpaneleng/power-of-2-choices-in-practice-b6097020dfad?source=rss-2ff3f89e407------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6097020dfad</guid>
            <category><![CDATA[columnar-databases]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[infrastructure]]></category>
            <dc:creator><![CDATA[Vijay Jayaram]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 18:04:06 GMT</pubDate>
            <atom:updated>2021-02-18T18:52:43.550Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>Access patterns dictate how data should be stored. Frequently written data should be in a row-oriented format, while frequently queried data should be in a column oriented format.</p><p>Mixpanel’s in-house database, Arb, supports both real-time event ingestion and fast analytical queries over all history. Storage nodes read data from a queue and write it to disk using a row-oriented write ahead log (WAL).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*woDwio8JJCMpEJUNKA8Z0g.png" /></figure><p>We run a service called compacter which converts data from the row format to a columnar format. This service runs in an autoscaling nodepool on Google Kubernetes Engine (GKE). When a storage node has a row file of a certain size or age, it sends a request to a random compacter node to compact it. The compacter returns either a handle to the resulting columnar file or an error. If all compacters are busy, they shed load and storage nodes retry with some backoff.</p><p>While compacter runs outside the critical path of queries, it must be reliable and efficient, since all new data in Arb passes through it daily. Given the nature of the work it has to do, the compacter service is very computationally expensive.</p><h3>Costs 📈</h3><p>Compacter costs grew steadily in the latter half of 2019, in part due to our growing customers and in part due to new use cases for data transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-9ShxEVXxpyd5-ZyJOwvg.png" /><figcaption>Monthly costs increased 60% over the course of 2019.</figcaption></figure><p>Worse yet, compacter failed to autoscale at the right times to absorb spikes in load. This resulted in engineers manually setting the autoscaler’s minimum number of replicas to a high number when load was high or during a service-wide incident. This cost us both in engineer time and money spent on wastefully provisioned instances.</p><h3>A Skew Problem</h3><p>We first looked at utilization, which for a compute-bound autoscaling service, we expected to be 80–90%. This assumption seemed reasonable because of the way Kubernetes’ <a href="https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/">Horizontal Pod Autoscaler</a> (HPA) works. You can configure it with a target service (compacter) and a target metric for that service (average CPU utilization of 90%). If CPU utilization exceeds the target by some threshold, it schedules more pods, and vice-versa if utilization is lower. Some <a href="https://en.wikipedia.org/wiki/Hysteresis#Control_systems">hysteresis</a> is built in to avoid constant thrashing.</p><p>In our case, however, average CPU utilization was ~40%. Averages can hide skew, so we plotted the median and 90th percentile utilization. This showed that half of the compacters did little work, while the top 10% were maxed out! Aggregate utilization was low because the autoscaling algorithm uses averages, not percentiles, to make its scaling decisions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/398/1*-IdX8hKebhB6cEaOihE3_Q.png" /><figcaption>Green line is p50 utilization, blue line is p90 utilization.</figcaption></figure><p>At first, we found this skew surprising:</p><ul><li>Storage nodes send requests to compacters based on a uniformly random distribution</li><li>Compacters receive 1000s of requests per minute, so through law of large numbers, these requests should have balanced over the 30–40 nodes we had.</li></ul><p>It turns out that even if you randomly distribute requests, skew can occur <em>when the individual load items have a very uneven distribution.</em> This happens in our case because of the vast range of customers we have, ranging from startups with thousands of events per day to large companies with billions per day. This type of power law, where your largest users are significantly larger than your smallest ones, makes simple averages a lot less useful.</p><h3>Exploring the Solution Space</h3><p>Once we identified skew as the issue, we considered a few solutions of varying complexity:</p><ul><li><strong>(High) Use a queue</strong>: Insert a queue between our storage nodes (clients) and compacters. This switches from the current push-model to an asynchronous pull-model, where compacters only take work when they have capacity. While this leads to optimal utilization, it requires a fundamental architecture change, adds a queue component, and requires keeping track of what compaction work is in-flight.</li><li><strong>(Medium) Use a proxy:</strong> Insert a load balancing service between storage nodes and compacters. This service can keep track of the load of all compacters, and forward incoming requests to the least loaded compacter. This maintains our current push-based architecture, but adds a proxy in between. We considered this, but decided to validate our hypothesis with something simpler.</li><li><strong>(Low) Power of 2 Random Choices (P2C)</strong>: The idea here is simple. Instead of storage nodes randomly picking 1 compacter, they randomly pick 2. They then ask each compacter for its current load, and send the request to the less loaded of the two. In theory, <a href="http://www.eecs.harvard.edu/~michaelm/NEWWORK/postscripts/twosurvey.pdf">this comes within a constant factor</a> of the above two solutions. We also wrote a <a href="https://github.com/ranic/loadbalancing/blob/master/main.py">quick Python simulation</a> to confirm our intuition on how this works.</li></ul><h3>Power of 2 Random Choices FTW!</h3><p>We started with the P2C approach because we could implement it in less than a day. And we were not disappointed. Here is the median and 90th percentile load across our compacter nodes before and after implementing Power of 2 balancing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukTAWUoPQziz9AO6dU1z5w.png" /><figcaption>The lines snap together because work is now evenly distributed!</figcaption></figure><p>With the above improvement to balancing, and a few other smaller tweaks, we could reliably use average utilization to autoscale and saw compacters react predictably to load spikes. In turn, we saw both our average utilization increase to ~90% and our error rate drop to nearly 0 in steady state since we no longer needed to shed load.</p><h3>Cost-Efficient Autoscaling with Preemptible VMs</h3><p>Given our increased confidence in the system’s behavior, we decided to take on a more advanced autoscaling strategy using preemptible VMs.</p><p>Preemptible VMs are low-cost VMs offered by Google which are ideal for stateless, background workloads. While 1/3rd the cost of regular VMs, they come at a reliability price: Google can arbitrarily terminate preemptible VMs when their capacity is limited.</p><p>We previously used preemptible VMs exclusively for Compacter. This was fine in the happy case, but catastrophic when Google would terminate them. So we decided to switch entirely to regular VMs, which improved reliability, but was more expensive.</p><p>This time, though, we wanted the best of both worlds: what if we could get the cost benefits of preemptible VMs in the common case, but with the reliability benefits of regular VMs in the worst case?</p><p>Turns out, we could! After doing some research and finding <a href="https://cloud.google.com/blog/products/containers-kubernetes/cutting-costs-with-google-kubernetes-engine-using-the-cluster-autoscaler-and-preemptible-vms">this excellent article</a>, we configured our nodepools such that Kubernetes will automatically try to use the cheaper VMs (when available) and fall back to the more expensive ones otherwise.</p><h3>Results</h3><p>We shipped both of these optimizations over the course of 2 weeks in January 2020, and they dropped our compacter service costs nearly 70%. Importantly, these stood the test of time with minimal follow-up from the team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*as5jVISR6UinJ5uq1hZbgw.png" /><figcaption>Costs dropped 70% and stayed down for the subsequent 6 months!</figcaption></figure><h3>Lessons Learned</h3><p>We learned a few lessons along the way that we hope are useful to teams building high scale services in the cloud:</p><p><strong>Autoscaling is hard to get right</strong>! It requires a high-signal target metric that is resilient to skew. In some cases, you can front your autoscaling service with a queue and autoscale on queue length. However, when callers block waiting for the result or an error, introducing a queue can add substantial complexity to the system.</p><p><strong>Be suspicious of averages</strong>. Always look at percentiles or a full distribution to better understand your load. Because of power law, there may be a few requests that constitute a significant part of your overall load.</p><p><strong>P2C is a remarkably simple trick to address skew</strong>. In subsequent months, we applied it to a few other compute-intensive autoscaling services at Mixpanel with similar success. That said, it’s not without tradeoffs. Here are two caveats to consider before using P2C:</p><ul><li><strong>It requires all clients to cooperate.</strong> If your service has just 1 client that you control, you can ensure that the client first checks for load and always sends requests to the less-loaded node. However if you have many clients, or ones that are out of your control, this does not work. If even one client doesn’t respect the power of 2 protocol, all bets are off in terms of skew! In our case, there are now a small number of internal clients to Compacter. We created a client library that encapsulates the P2C logic and other conveniences, which all clients use. If clients are truly external, it’s better to use an off-the-shelf proxy/load balancer to route requests (which may itself use P2C under the hood!).</li><li><strong>It introduces two extra round trips</strong> on each request to check load on 2 random nodes. This overhead is fine when the actual requests are somewhat heavy (like in our case) and client-server latency is negligible (eg: internal services in a single GCP zone). It’s not fine when the requests themselves are small or the round-trip latency between client and server is high.</li></ul><p>If you’re interested in creative solutions to challenging infrastructure problems, we’re hiring! Reach out to us via our <a href="http://mixpanel.com/careers">careers page</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6097020dfad" width="1" height="1" alt=""><hr><p><a href="https://medium.com/mixpaneleng/power-of-2-choices-in-practice-b6097020dfad">Power-of-2-Choices in Practice</a> was originally published in <a href="https://medium.com/mixpaneleng">Mixpanel Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>