<?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:media="http://search.yahoo.com/mrss/">
    <channel>
        <title><![CDATA[Tiger Data Blog]]></title>
        <description><![CDATA[Insights, product updates, and tips from TigerData (Creators of TimescaleDB) engineers on Postgres, time series & AI. IoT, crypto, and analytics tutorials & use cases.]]></description>
        <link>https://www.tigerdata.com/blog</link>
        <image>
            <url>https://www.tigerdata.com/icon.ico</url>
            <title>Tiger Data Blog</title>
            <link>https://www.tigerdata.com/blog</link>
        </image>
        <generator>RSS for Node</generator>
        <lastBuildDate>Tue, 07 Apr 2026 13:05:37 GMT</lastBuildDate>
        <atom:link href="https://www.tigerdata.com/blog" rel="self" type="application/rss+xml"/>
        <ttl>60</ttl>
        <item>
            <title><![CDATA[Understanding PostgreSQL Aggregation and Hyperfunctions’ Design]]></title>
            <description><![CDATA[A discussion of aggregation in PostgreSQL and how it integrates with the design of Timescale’s hyperfunctions.

]]></description>
            <link>https://www.tigerdata.com/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design</link>
            <guid isPermaLink="true">https://www.tigerdata.com/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design</guid>
            <category><![CDATA[Product & Engineering]]></category>
            <category><![CDATA[PostgreSQL]]></category>
            <category><![CDATA[Analytics]]></category>
            <dc:creator><![CDATA[David Kohn]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 17:06:03 GMT</pubDate>
            <media:content medium="image" href="https://timescale.ghost.io/blog/content/images/2024/01/PostgreSQL-Aggregation-and-Hyperfunctions-Design--1-.png">
            </media:content>
            <content:encoded><![CDATA[<p>At Timescale, our goal is always to focus on the developer experience, and we take great care to design our products and APIs to be developer-friendly. This focus on developer experience is why we decided <a href="https://timescale.ghost.io/blog/blog/when-boring-is-awesome-building-a-scalable-time-series-database-on-postgresql-2900ea453ee2/">early in the design of TimescaleDB to build on top of PostgreSQL</a>. We believed then, as we do now, that building on the world’s fastest-growing database would have numerous benefits for our users.</p><p>The same logic applies to many of our features, including <a href="https://www.timescale.com/learn/time-series-data-analysis-hyperfunctions" rel="noreferrer">hyperfunctions</a>. Timescale's hyperfunctions are designed to enhance PostgreSQL's native aggregation capabilities—<a href="https://timescale.ghost.io/blog/introducing-hyperfunctions-new-sql-functions-to-simplify-working-with-time-series-data-in-postgresql/" rel="noreferrer">a series of SQL functions within TimescaleDB that make it easier to manipulate and analyze time-series data in PostgreSQL with fewer lines of code</a>.</p><p>So, let's have a closer look at how PostgreSQL aggregation works and how it has influenced the design of Timescale's hyperfunctions.</p><div class="kg-card kg-callout-card kg-callout-card-purple"><div class="kg-callout-emoji">✨</div><div class="kg-callout-text">Before we start, here's a recap on <a href="https://www.timescale.com/learn/understanding-sql-aggregate-functions" rel="noreferrer">SQL aggregate functions</a> and how to use them.</div></div><h2 id="a-primer-on-postgresql-aggregation">A Primer on PostgreSQL Aggregation</h2><p>We'll start by going over PostgreSQL aggregates. But first, a little backstory.</p><p>When I first started learning about PostgreSQL five or six years ago (I was an electrochemist and was dealing with lots of battery data, as mentioned in <a href="https://timescale.ghost.io/blog/blog/what-time-weighted-averages-are-and-why-you-should-care/">my last post on time-weighted averages</a>), I ran into some performance issues. I was trying to understand better what was happening inside the database to improve its performance—and that’s when I found <a href="https://momjian.us">Bruce Momjian</a>’s talks on <a href="https://momjian.us/main/presentations/internals.html">PostgreSQL Internals Through Pictures</a>. Bruce is well-known in the community for his insightful talks (and his penchant for bow ties); his sessions were a revelation for me. </p><p>They’ve served as a foundation for my understanding of how PostgreSQL works ever since. He explained things so clearly, and I’ve always learned best when I can visualize what’s going on, so the “through pictures” part really helped—and stuck with—me. </p><p>So, this next bit is my attempt to channel Bruce by explaining some PostgreSQL internals through pictures. Cinch up your bow ties and get ready for some learnin'.</p>
<!--kg-card-begin: html-->
<figure>
	<iframe height="100px" width="100px" style="min-width: 100%; min-height: 330px" 		src="https://s3.amazonaws.com/blog.timescale.com/gifs/player.html?source=https://s3.amazonaws.com/blog.timescale.com/gifs/how-postgres-works/david_bowtie.mp4" frameborder="0" class="gif-stand-in">
	</iframe>
    <figcaption class="gif-caption">The author pays homage to Bruce Momjian (and looks rather pleased with himself because he’s managed to tie a bow tie on the first try).
    </figcaption>
</figure>

<!--kg-card-end: html-->
<h3 id="postgresql-aggregates-vs-functions">PostgreSQL aggregates vs. functions</h3><p>We have written about <a href="https://timescale.ghost.io/blog/blog/introducing-hyperfunctions-new-sql-functions-to-simplify-working-with-time-series-data-in-postgresql/">how we use custom functions and aggregates to extend SQL</a>, but we haven’t exactly explained the difference<em> between</em> them.</p><p>The fundamental difference between an aggregate function and a “regular” function in SQL is that an <strong>aggregate</strong> produces a single result from a <em>group</em> of related rows, while a regular <strong>function </strong>produces a result for <em>each</em> row:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/Aggregate-vs.-Function-2.jpg" class="kg-image" alt="A side-by-side diagram depicting an “aggregate” side and a “function” side and how each product results. There are three individual rows on the aggregate side, with arrows that point to a single result; on the function side, there are three individual rows, with arrows that point to three different results (one per row). " loading="lazy" width="1804" height="752" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/Aggregate-vs.-Function-2.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/Aggregate-vs.-Function-2.jpg 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2021/08/Aggregate-vs.-Function-2.jpg 1600w, https://timescale.ghost.io/blog/content/images/2021/08/Aggregate-vs.-Function-2.jpg 1804w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">In SQL, aggregates produce a result from multiple rows, while functions produce a result per row.</span></figcaption></figure><p>This is not to say that a function can’t have inputs from multiple columns; they just have to come from the same row. </p><p>Another way to think about it is that functions often act on rows, whereas aggregates act on columns. To illustrate this, let’s consider a theoretical table <code>foo</code> with two columns:</p><pre><code class="language-SQL">CREATE TABLE foo(
	bar DOUBLE PRECISION,
	baz DOUBLE PRECISION);
</code></pre><p>And just a few values so we can easily see what’s going on:</p><pre><code class="language-SQL">INSERT INTO foo(bar, baz) VALUES (1.0, 2.0), (2.0, 4.0), (3.0, 6.0);
</code></pre><p>The function <a href="https://www.postgresql.org/docs/13/functions-conditional.html#FUNCTIONS-GREATEST-LEAST"><code>greatest()</code></a> will produce the largest of the values in columns <code>bar</code> and <code>baz</code> for each row:</p><p></p><pre><code class="language-SQL">SELECT greatest(bar, baz) FROM foo; 
 greatest 
----------
        2
        4
        6
</code></pre><p>Whereas the aggregate <a href="https://www.postgresql.org/docs/current/functions-aggregate.html"><code>max()</code></a> will produce the largest value from each column:</p><pre><code class="language-SQL">SELECT max(bar) as bar_max, max(baz) as baz_max FROM foo;

 bar_max | baz_max 
---------+---------
       3 |       6
</code></pre><p>Using the above data, here’s a picture of what happens when we aggregate something:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/Aggregate-vs.-Function-1-1.jpg" class="kg-image" alt="A diagram showing how the statement: `SELECT max(bar) FROM foo;` works: multiple rows with values of “bar equal to” 1.0, 2.0, and 3.0, go through the `max(bar)` aggregate to ultimately produce a result of 3.0. " loading="lazy" width="1804" height="600" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/Aggregate-vs.-Function-1-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/Aggregate-vs.-Function-1-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2021/08/Aggregate-vs.-Function-1-1.jpg 1600w, https://timescale.ghost.io/blog/content/images/2021/08/Aggregate-vs.-Function-1-1.jpg 1804w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">The </span><code spellcheck="false" style="white-space: pre-wrap;"><span>max()</span></code><span style="white-space: pre-wrap;"> aggregate gets the largest value from multiple rows.</span></figcaption></figure><p>The aggregate takes inputs from multiple rows and produces a single result. That’s the main difference between it and a function, but how does it do that? Let’s look at what it’s doing under the hood.</p><h3 id="aggregate-internals-row-by-row">Aggregate internals: Row-by-row</h3><p>Under the hood, aggregates in PostgreSQL work row-by-row. But then, how does an aggregate know anything about the previous rows?</p><p>An aggregate stores some state about the rows it has previously seen, and as the database sees new rows, it updates that internal state.</p><p>For the <code>max()</code> aggregate we’ve been discussing, the internal state is simply the largest value we’ve collected so far. </p><p>Let’s take this step-by-step.</p><p>When we start, our internal state is <code>NULL</code> because we haven’t seen any rows yet:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/1-2.jpg" class="kg-image" alt="Flowchart arrow diagram representing the max open parens bar close parens aggregate, with three rows below the arrow where bar is equal to 1.0, 2.0, and 3.0, respectively. There is a box in the arrow in which the state is equal to NULL. " loading="lazy" width="1600" height="904" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/1-2.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/1-2.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/1-2.jpg 1600w" sizes="(min-width: 720px) 720px"></figure><p>Then, we get our first row in:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/2-2.jpg" class="kg-image" alt="" loading="lazy" width="1600" height="904" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/2-2.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/2-2.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/2-2.jpg 1600w" sizes="(min-width: 720px) 720px"></figure><p>Since our state is <code>NULL</code>, we initialize it to the first value we see:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/3-1.jpg" class="kg-image" alt="The same flowchart diagram, except that row one has moved _out_ of the arrow, and the state has been updated from NULL to the 1.0, row one’s value. " loading="lazy" width="1600" height="904" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/3-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/3-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/3-1.jpg 1600w" sizes="(min-width: 720px) 720px"></figure><p>Now, we get our second row:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/4-2.jpg" class="kg-image" alt="The same flowchart diagram, except that row two has moved into the arrow representing the max aggregate. " loading="lazy" width="1600" height="904" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/4-2.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/4-2.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/4-2.jpg 1600w" sizes="(min-width: 720px) 720px"></figure><p>And we see that the value of bar (2.0) is greater than our current state (1.0), so we update the state:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/5-2.jpg" class="kg-image" alt=" The same diagram, except that row two has moved out of the max aggregate, and the state has been updated to the largest value (the value of row two, 2.0). " loading="lazy" width="1600" height="904" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/5-2.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/5-2.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/5-2.jpg 1600w" sizes="(min-width: 720px) 720px"></figure><p>Then, the next row comes into the aggregate:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/6-1.jpg" class="kg-image" alt="The same diagram, except that the row three has moved into the arrow representing the max aggregate. " loading="lazy" width="1600" height="904" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/6-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/6-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/6-1.jpg 1600w" sizes="(min-width: 720px) 720px"></figure><p>We compare it to our current state, take the greatest value, and update our state:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/7-1.jpg" class="kg-image" alt="The same diagram, expect that row three has moved out of the max aggregate, and the state has been updated to the largest value, the value of the third row, 3.0." loading="lazy" width="1600" height="904" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/7-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/7-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/7-1.jpg 1600w" sizes="(min-width: 720px) 720px"></figure><p>Finally, we don’t have any more rows to process, so we output our result:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/8-1.jpg" class="kg-image" alt="The same diagram, now noting that there are “no more rows” to process, and including a final result, 3.0, being output at the end of the arrow. " loading="lazy" width="1600" height="904" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/8-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/8-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/8-1.jpg 1600w" sizes="(min-width: 720px) 720px"></figure><p>So, to summarize, each row comes in, gets compared to our current state, and then the state gets updated to reflect the new greatest value. Then the next row comes in, and we repeat the process until we’ve processed all our rows and output the result.</p>
<!--kg-card-begin: html-->
    <video autoplay loop muted playsinline>
      <source id="player" src="https://s3.amazonaws.com/blog.timescale.com/gifs/how-postgres-works/how_postgres_works_1.mp4" type="video/mp4"></source>
    </video>
    <figcaption class="gif-caption">The max aggregate aggregation process, told in GIFs. 
    </figcaption>
<!--kg-card-end: html-->
<p></p><p>There’s a name for the function that processes each row and updates the internal state: the <a href="https://www.postgresql.org/docs/current/sql-createaggregate.html"><strong>state transition function</strong></a> (or just “transition function” for short.) The transition function for an aggregate takes the current state and the value from the incoming row as arguments and produces a new state. </p><p>It’s defined like this, where <code>current_value</code> represents values from the incoming row, <code>current_state</code> represents the current aggregate state built up over the previous rows (or NULL if we haven’t yet gotten any), and <code>next_state</code> represents the output after analyzing the incoming row:</p><pre><code class="language-SQL">next_state = transition_func(current_state, current_value)</code></pre><h3 id="aggregate-internals-composite-state">Aggregate internals: Composite state</h3><p>So, the <code>max()</code> aggregate has a straightforward state that contains just one value (the largest we’ve seen). But not all aggregates in PostgreSQL have such a simple state.</p><p>Let’s consider the aggregate for average (<code>avg</code>):</p><pre><code class="language-SQL">SELECT avg(bar) FROM foo;</code></pre><p>To refresh, an average is defined as:</p><p>\begin{equation} avg(x) = \frac{sum(x)}{count(x)}  \end{equation}</p>
<p>To calculate it, we store the sum and the count as our internal state and update our state as we process rows:</p>
<!--kg-card-begin: html-->
    <video autoplay loop muted playsinline>
      <source id="player" src="https://s3.amazonaws.com/blog.timescale.com/gifs/how-postgres-works/how_postgres_works_2.mp4" type="video/mp4"></source>
    </video>
    <figcaption class="gif-caption">The `avg()` aggregation process, told in GIFs. For `avg()`, the transition function must update a more complex state since the sum and count are stored separately at each aggregation step. 
    </figcaption>
<!--kg-card-end: html-->
<p>But, when we’re ready to output our result for <code>avg</code>, we need to divide <code>sum</code> by <code>count</code>:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/9-1.jpg" class="kg-image" alt="An arrow flowchart diagram similar to those before, showing the end state of the avg aggregate. The rows have moved through the aggregate, and the state is 6.0 - the sum and three - the count. There are then some question marks and an end result of 2.0." loading="lazy" width="1600" height="904" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/9-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/9-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/9-1.jpg 1600w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">For some aggregates, we can output the state directly – but for others, we need to perform an operation on the state before calculating our final result.</span></figcaption></figure><p>There’s another function inside the aggregate that performs this calculation: the <a href="https://www.postgresql.org/docs/current/sql-createaggregate.html"><strong>final function</strong></a>. Once we’ve processed all the rows, the final function takes the state and does whatever it needs to produce the result. </p><p>It’s defined like this, where <code>final_state</code> represents the output of the transition function after it has processed all the rows:</p><pre><code class="language-SQL">result = final_func(final_state)
</code></pre><p>And, through pictures:</p>
<!--kg-card-begin: html-->
    <video autoplay loop muted playsinline>
      <source id="player" src="https://s3.amazonaws.com/blog.timescale.com/gifs/how-postgres-works/how_postgres_works_3.mp4" type="video/mp4"></source>
    </video>
    <figcaption class="gif-caption">How the average aggregate works, told in GIFs. Here, we’re highlighting the role of the final function.
    </figcaption>
<!--kg-card-end: html-->
<p>To summarize, as an aggregate scans over rows, its <strong>transition function</strong> updates its internal state. Once the aggregate has scanned all of the rows, its <strong>final function</strong> produces a result, which is returned to the user.</p><h3 id="improving-the-performance-of-aggregate-functions">Improving the performance of aggregate functions</h3><p>One interesting thing to note here: the transition function is called many, many more times than the final function: once for each row, whereas the final function is called once per <em>group</em> of rows. </p><p>Now, the transition function isn’t inherently more expensive than the final function on a per-call basis—but because there are usually orders of magnitude more rows going into the aggregate than coming out, the transition function step becomes the most expensive part very quickly. This is especially true when you have high-volume time-series data being ingested at high rates; optimizing aggregate transition function calls is important for improving performance.</p><p>Luckily, PostgreSQL already has ways to optimize aggregates.</p><h3 id="parallelization-and-the-combine-function">Parallelization and the combine function</h3><p>Because the transition function is run on each row, <a href="https://www.postgresql.org/message-id/flat/CA%2BTgmoYSL_97a--qAvdOa7woYamPFknXsXX17m0t2Pwc%2BFOvYw%40mail.gmail.com#fb9f2ae2a52ac605a4439a1879ff3c10">some enterprising PostgreSQL developers</a> asked: <em>what if we parallelized the transition function calculation?</em> </p><p>Let’s revisit our definitions for transition functions and final functions:</p><pre><code class="language-SQL">next_state = transition_func(current_state, current_value)

result = final_func(final_state)</code></pre><p>We can run this in parallel by instantiating multiple copies of the transition function and handing a subset of rows to each instance. Then, each parallel aggregate will run the transition function over the subset of rows it sees, producing multiple (partial) states, one for each parallel aggregate. But, since we need to aggregate over the <em>entire</em> data set, we can’t run the final function on each parallel aggregate separately because they only have some of the rows. </p><p>So, now we’ve ended up in a bit of a pickle: we have multiple partial aggregate states, and the final function is only meant to work on the single, final state—right before we output the result to the user. </p><p>To solve this problem, we need a new type of function that combines two partial states into one so that the final function can do its work. This is (aptly) called the <a href="https://www.postgresql.org/docs/current/sql-createaggregate.html"><strong>combine function</strong></a>. </p><p>We can run the combine function iteratively over all of the partial states that are created when we parallelize the aggregate.</p><pre><code class="language-SQL">combined_state = combine_func(partial_state_1, partial_state_2)</code></pre><p>For instance, in <code>avg</code>, the combine function will add up the counts and sums.</p>
<!--kg-card-begin: html-->
    <video autoplay loop muted playsinline>
      <source id="player" src="https://s3.amazonaws.com/blog.timescale.com/gifs/how-postgres-works/how_postgres_works_4.mp4" type="video/mp4"></source>
    </video>
    <figcaption class="gif-caption">How parallel aggregation works, told in GIFs. Here, we’re highlighting the combine function (We’ve added a couple more rows to illustrate parallel aggregation.)
    </figcaption>
<!--kg-card-end: html-->
<p>Then, after we have the combined state from all of our parallel aggregates, we run the final function and get our result.</p><h3 id="deduplication">Deduplication</h3><p>Parallelization and the combined function are one way to reduce the cost of calling an aggregate, but they’re not the only way. </p><p>One other built-in <a href="https://www.tigerdata.com/blog/best-practices-for-query-optimization-in-postgresql" rel="noreferrer">PostgreSQL optimization</a> that reduces an aggregate’s cost occurs in a statement like this:</p><pre><code class="language-SQL">SELECT avg(bar), avg(bar) / 2 AS half_avg FROM foo;</code></pre><p>PostgreSQL will optimize this statement to evaluate the <code>avg(bar)</code> calculation only once and then use that result twice. </p><p>And what if we have different aggregates with the same transition function but different final functions? PostgreSQL further optimizes by calling the transition function (the expensive part) on all the rows and then doing both final functions! Pretty neat!</p><p>That’s not all that PostgreSQL aggregates can do, but it’s a pretty good tour, and it’s enough to get us where we need to go today.</p><h2 id="two-step-aggregation-in-timescaledb-hyperfunctions">Two-step Aggregation in TimescaleDB Hyperfunctions</h2><p>In TimescaleDB, we’ve implemented the two-step aggregation design pattern for our aggregate functions. This generalizes the PostgreSQL internal aggregation API and exposes it to the user via our aggregates, accessors, and rollup functions. (In other words, each internal <a href="https://www.tigerdata.com/blog/function-pipelines-building-functional-programming-into-postgresql-using-custom-operators" rel="noreferrer">PostgreSQL function</a> has an equivalent function in TimescaleDB hyperfunctions.)</p><p>As a refresher, when we talk about the two-step aggregation design pattern, we mean the following convention, where we have an inner aggregate call:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/Inner-aggregate-call-1.jpg" class="kg-image" alt="SELECT average(time_weight('LOCF', value)) as time_weighted_average FROM foo; -- or SELECT approx_percentile(0.5, percentile_agg(value)) as median FROM bar;  With the snippets: time_weight('LOCF', value) and percentile_agg(value) highlighted." loading="lazy" width="1232" height="230" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/Inner-aggregate-call-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/Inner-aggregate-call-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/Inner-aggregate-call-1.jpg 1232w" sizes="(min-width: 720px) 720px"></figure><p>And an outer accessor call:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/Outer-accessor-call-1.jpg" class="kg-image" alt="The same as the previous in terms of code, except the sections: average(time_weight('LOCF', value)) and approx_percentile(0.5, percentile_agg(value)) are highlighted" loading="lazy" width="1232" height="230" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/Outer-accessor-call-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/Outer-accessor-call-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/Outer-accessor-call-1.jpg 1232w" sizes="(min-width: 720px) 720px"></figure><p>The inner aggregate call returns the internal state, just like the transition function does in PostgreSQL aggregates. </p><p>The outer accessor call takes the internal state and returns a result to the user, just like the final function does in PostgreSQL. </p><p>We also have special <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/rollup-percentile/#sample-usage"><code>rollup</code></a> functions <a href="https://docs.timescale.com/api/latest/hyperfunctions/time-weighted-averages/rollup-timeweight/">defined for each of our aggregates</a> that work much like PostgreSQL combine functions.</p>
<!--kg-card-begin: html-->
<span id="agg-table" />
<!--kg-card-end: html-->
<figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/table-pg-two-step-comparison-1.jpg" class="kg-image" alt="A table with columns labeled: the PostgreSQL internal aggregation API, Two-step aggregate equivalent, and TimescaleDB hyperfunction example. In the first row, we have the transition function equivalent to the aggregate, and the examples are time_weight() and percentile_agg(). In the second row, we have the final function, equivalent to the accessor, and the examples are average() and approx_percentile(). In the third row, we have the combine function equivalent to rollup in two-step aggregates, and the example is rollup()." loading="lazy" width="1109" height="466" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/table-pg-two-step-comparison-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/table-pg-two-step-comparison-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/table-pg-two-step-comparison-1.jpg 1109w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">PostgreSQL internal aggregation APIs and their TimescaleDB hyperfunctions’ equivalent</span></figcaption></figure><h3 id="why-we-use-the-two-step-aggregate-design-pattern">Why we use the two-step aggregate design pattern</h3><p>There are four basic reasons we expose the two-step aggregate design pattern to users rather than leave it as an internal structure (and the last two helped us build our continuous aggregates): </p><ol><li>Allow multi-parameter aggregates to re-use state, making them more efficient.</li><li>Cleanly distinguish between parameters that affect aggregates vs. accessors, making performance implications easier to understand and predict.</li><li>Enable easy-to-understand rollups, with logically consistent results, in continuous aggregates and window functions (one of our most common requests on continuous aggregates).</li><li>Allow easier <em>retrospective analysis</em> of downsampled data in continuous aggregates as requirements change, but the data is already gone.</li></ol><p>That’s a little theoretical, so let’s dive in and explain each one.</p><h2 id="efficiency-of-two-step-aggregates">Efficiency of Two-Step Aggregates<br></h2><h3 id="re-using-state"><strong>Re-using state</strong></h3><p>PostgreSQL is very good at optimizing statements (as we saw earlier in this post through pictures 🙌), but you have to give it things in a way it can understand. </p><p>For instance, <a href="https://timescale.ghost.io/blog/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design-2/#deduplication">when we talked about deduplication</a>, we saw that PostgreSQL could “figure out” when a statement occurs more than once in a query (i.e., <code>avg(bar)</code>) and only run the statement a single time to avoid redundant work:</p><pre><code class="language-SQL">SELECT avg(bar), avg(bar) / 2 AS half_avg FROM foo;</code></pre><p>This works because the <code>avg(bar)</code> occurs multiple times without variation. </p><p>However, if I write the equation in a slightly different way and move the division<em> inside</em> the parentheses so that the expression <code>avg(bar)</code> doesn’t repeat so neatly, PostgreSQL <em>can’t</em> figure out how to optimize it:</p><pre><code class="language-SQL">SELECT avg(bar), avg(bar / 2) AS half_avg FROM foo;</code></pre><p>It doesn’t know that the division is commutative or that those two queries are equivalent. </p><p>This is a complicated problem for database developers to solve, and thus, as a PostgreSQL user, you need to make sure to write your query in a way that the database can understand. </p><p>Performance problems caused by equivalent statements that the database doesn’t understand are equal (or that are equal in the specific case you wrote but not in the general case) can be some of the trickiest SQL optimizations to figure out as a user. </p><p>Therefore, <strong>when we design our APIs, we try to make it hard for users to write low-performance code unintentionally: in other words, the default option should be the high-performance option</strong>.</p><p>For the next bit, it’ll be useful to have a simple table defined as:</p><pre><code class="language-SQL">CREATE TABLE foo(
	ts timestamptz, 
	val DOUBLE PRECISION);</code></pre><p>Let’s look at an example of how we use two-step aggregation in the <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/">percentile approximation hyperfunction</a> to allow PostgreSQL to optimize performance.</p><pre><code class="language-SQL">SELECT 
    approx_percentile(0.1, percentile_agg(val)) as p10, 
    approx_percentile(0.5, percentile_agg(val)) as p50, 
    approx_percentile(0.9, percentile_agg(val)) as p90 
FROM foo;</code></pre><p>...is treated as the same as:</p><pre><code class="language-SQL">SELECT 
    approx_percentile(0.1, pct_agg) as p10, 
    approx_percentile(0.5, pct_agg) as p50, 
    approx_percentile(0.9, pct_agg) as p90 
FROM 
(SELECT percentile_agg(val) as pct_agg FROM foo) pct;
</code></pre><p>This calling convention allows us to use identical aggregates so that, under the hood, PostgreSQL can deduplicate calls to the identical aggregates (and is faster as a result).</p><p>Now, let’s compare this to the one-step aggregate approach. </p><p>PostgreSQL can’t deduplicate aggregate calls here because the extra parameter in the <code>approx_percentile</code> aggregate changes with each call:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2021/08/Approx_percentile.jpg" class="kg-image" alt="-- NB: THIS IS AN EXAMPLE OF AN API WE DECIDED NOT TO USE, IT DOES NOT WORK SELECT      approx_percentile(0.1, val) as p10,      approx_percentile(0.5, val) as p50,      approx_percentile(0.9, val) as p90  FROM foo; The first values in each of the approx_percentile calls are highlighted and in red." loading="lazy" width="1232" height="368" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/Approx_percentile.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/08/Approx_percentile.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/08/Approx_percentile.jpg 1232w" sizes="(min-width: 720px) 720px"></figure><p>So, even though all of those functions could use the same approximation built up over all the rows, PostgreSQL has no way of knowing that. The two-step aggregation approach enables us to structure our calls so that PostgreSQL can optimize our code, and it enables developers to understand when things will be more expensive and when they won't. Multiple different aggregates with different inputs will be expensive, whereas multiple accessors to the same aggregate will be much less expensive.</p><h3 id="cleanly-distinguishing-between-aggregateaccessor-parameters">Cleanly distinguishing between aggregate/accessor parameters</h3><p>We also chose the two-step aggregate approach because some of our aggregates can take multiple parameters or options themselves, and their accessors can also take options:</p><pre><code class="language-SQL">SELECT
    approx_percentile(0.5, uddsketch(1000, 0.001, val)) as median,--1000 buckets, 0.001 target err
    approx_percentile(0.9, uddsketch(1000, 0.001, val)) as p90, 
    approx_percentile(0.5, uddsketch(100, 0.01, val)) as less_accurate_median -- modify the terms for the aggregate get a new approximation
FROM foo;</code></pre><p><br>That’s an example of <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/percentile-aggregation-methods/uddsketch/"><code>uddsketch</code></a>, an <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/percentile-aggregation-methods/#choosing-the-right-algorithm-for-your-use-case">advanced aggregation method</a> for percentile approximation that can take its own parameters. </p><p>Imagine if the parameters were jumbled together in one aggregate:</p><pre><code class="language-SQL">-- NB: THIS IS AN EXAMPLE OF AN API WE DECIDED NOT TO USE, IT DOES NOT WORK
SELECT
    approx_percentile(0.5, 1000, 0.001, val) as median
FROM foo;
</code></pre><p><br>It’d be pretty difficult to understand which argument is related to which part of the functionality.</p><p>Conversely, the two-step approach separates the arguments to the accessor vs. aggregate very cleanly, where the aggregate function is defined in parenthesis within the inputs of our final function:</p><pre><code class="language-SQL">SELECT
    approx_percentile(0.5, uddsketch(1000, 0.001, val)) as median
FROM foo;
</code></pre><p>By making it clear which is which, users can know that if they change the inputs to the aggregate, they will get more (costly) aggregate nodes, =while inputs to the accessor are cheaper to change. </p><p>So, those are the first two reasons we expose the API—and what it allows developers to do as a result. The last two reasons involve continuous aggregates and how they relate to hyperfunctions, so first, a quick refresher on what they are.</p><h2 id="continuous-aggregates-and-two-step-design-in-timescaledb">Continuous Aggregates and Two-Step Design in TimescaleDB</h2><p>TimescaleDB includes a feature called <a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/continuous-aggregates/">continuous aggregates</a>, which are designed to make queries on very large datasets run faster. TimescaleDB's continuous aggregates continuously and incrementally store the results of an aggregation query in the background, so when you run the query, only the data that has changed needs to be computed, not the entire dataset. </p><p>In our discussion of the combine function <a href="https://timescale.ghost.io/blog/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design-2/#deduplication">above,</a> we covered how you could take the expensive work of computing the transition function over every row and split the rows over multiple parallel aggregates to speed up the calculation.</p><p>TimescaleDB continuous aggregates do something similar, except they spread the computation work over<em> time</em> rather than between parallel processes running simultaneously. The continuous aggregate computes the transition function over a subset of rows inserted some time in the past, stores the result, and then, at query time, we only need to compute over the raw data for a small section of recent time that we haven’t yet calculated. </p><p>When we designed TimescaleDB hyperfunctions, we wanted them to work well within continuous aggregates and even open new possibilities for users.  </p><p>Let’s say I create a continuous aggregate from the simple table above to compute the sum, average, and percentile (the latter using a hyperfunction) in 15-minute increments:</p><pre><code class="language-SQL">CREATE MATERIALIZED VIEW foo_15_min_agg
WITH (timescaledb.continuous)
AS SELECT id,
    time_bucket('15 min'::interval, ts) as bucket,
    sum(val),
    avg(val),
    percentile_agg(val)
FROM foo
GROUP BY id, time_bucket('15 min'::interval, ts);</code></pre><p>And then what if I come back and I want to re-aggregate it to hours or days rather than 15-minute buckets—or need to aggregate my data across all IDs? Which aggregates can I do that for, and which can’t I?</p><h3 id="logically-consistent-rollups">Logically consistent rollups</h3><p>One of the problems we wanted to solve with two-step aggregation was how to convey to the user when it is “okay” to re-aggregate and when it’s not. (By “okay,” I mean you would get the same result from the re-aggregated data as you would running the aggregate on the raw data directly.) </p><p>For instance:</p><pre><code class="language-SQL">SELECT sum(val) FROM tab;
-- is equivalent to:
SELECT sum(sum) 
FROM 
    (SELECT id, sum(val) 
    FROM tab
    GROUP BY id) s;</code></pre><p>But:</p><pre><code class="language-SQL">SELECT avg(val) FROM tab;
-- is NOT equivalent to:
SELECT avg(avg) 
FROM 
    (SELECT id, avg(val) 
    FROM tab
    GROUP BY id) s;
</code></pre><p>Why is re-aggregation okay for <code>sum</code> but not for <code>avg</code>? </p><p>Technically, it’s logically consistent to re-aggregate when:</p><ul><li>The aggregate returns the internal aggregate state. The internal aggregate state for sum is <code>(sum)</code>, whereas for average, it is <code>(sum, count)</code>. </li><li>The aggregate’s combine and transition functions are equivalent. For <code>sum()</code>, the states and the operations are the same. For <code>count()</code>, the <em>states</em> are the same, but the transition and combine functions <em>perform different operations </em>on them. <code>sum()</code>’s transition function adds the incoming value to the state, and its combine function adds two states together or a sum of sums.  Conversely, <code>count()</code>s transition function increments the state for each incoming value, but its combine function adds two states together, or a sum of counts.</li></ul><p>But, you have to have in-depth (and sometimes rather arcane) knowledge about each aggregate’s internals to know which ones meet the above criteria—and, therefore, which ones you can re-aggregate.</p><p><strong>With the two-step aggregate approach, we can convey when it is logically consistent to re-aggregate by exposing our equivalent of the combine function when the aggregate allows it.</strong></p><p>We call that function <code>rollup()</code>. <code>Rollup()</code> takes multiple inputs from the aggregate and combines them into a single value. </p><p>All of our aggregates that can be combined have <code>rollup</code> functions that will combine the output of the aggregate from two different groups of rows. (Technically, <code>rollup()</code> is an aggregate function because it acts on multiple rows. For clarity, I’ll call them rollup functions to distinguish them from the base aggregate).  Then you can call the accessor on the combined output! </p><p>So using that continuous aggregate we created to get a 1-day re-aggregation of our <code>percentile_agg</code> becomes as simple as:</p><pre><code class="language-SQL">SELECT id, 
    time_bucket('1 day'::interval, bucket) as bucket, 
    approx_percentile(0.5, rollup(percentile_agg)) as median
FROM foo_15_min_agg
GROUP BY id, time_bucket('1 day'::interval, bucket);</code></pre><p>(We actually suggest that you create your continuous aggregates without calling the accessor function for this very reason. Then, you can just create views over top or put the accessor call in your query). </p><p>This brings us to our final reason.</p><h3 id="retrospective-analysis-using-continuous-aggregates">Retrospective analysis using continuous aggregates</h3><p>When we create a continuous aggregate, we’re defining a view of our data that we could then be stuck with for a very long time. </p><p>For example, we might have a data retention policy that deletes the underlying data after X time period. If we want to go back and re-calculate anything, it can be challenging, if not impossible, since we’ve “dropped” the data. </p><p>But we understand that in the real world, you don’t always know what you’re going to need to analyze ahead of time. </p><p>Thus, we designed hyperfunctions to use the two-step aggregate approach so they would better integrate with continuous aggregates. As a result, users store the aggregate state in the continuous aggregate view and modify accessor functions <em>without</em> requiring them to recalculate old states that might be difficult (or impossible) to reconstruct (because the data is archived, deleted, etc.). </p><p>The two-step aggregation design also allows for much greater flexibility with continuous aggregates. For instance, let’s take a continuous aggregate where we do the aggregate part of the two-step aggregation like this:</p><pre><code class="language-SQL">CREATE MATERIALIZED VIEW foo_15_min_agg
WITH (timescaledb.continuous)
AS SELECT id,
    time_bucket('15 min'::interval, ts) as bucket,
    percentile_agg(val)
FROM foo
GROUP BY id, time_bucket('15 min'::interval, ts);
</code></pre><p>When we first create the aggregate, we might only want to get the median:</p><pre><code class="language-SQL">SELECT
    approx_percentile(0.5, percentile_agg) as median
FROM foo_15_min_agg;
</code></pre><p>But then, later, we decided we wanted to know the 95th percentile as well. </p><p>Luckily, we don’t have to modify the continuous aggregate; we<strong> just modify the parameters to the accessor function in our original query to return the data we want from the aggregate state</strong>:</p><pre><code class="language-SQL">SELECT
    approx_percentile(0.5, percentile_agg) as median,
    approx_percentile(0.95, percentile_agg) as p95
FROM foo_15_min_agg;</code></pre><p>And then, if a year later, we want the 99th percentile as well, we can do that too:</p><pre><code class="language-SQL">SELECT
    approx_percentile(0.5, percentile_agg) as median,
    approx_percentile(0.95, percentile_agg) as p95,
    approx_percentile(0.99, percentile_agg) as p99
FROM foo_15_min_agg;
</code></pre><p>That’s just scratching the surface. Ultimately, our goal is to provide a high level of developer productivity that enhances other PostgreSQL and TimescaleDB features, like aggregate deduplication and continuous aggregates.</p><h2 id="example-time-weighted-average">Example: Time-Weighted Average</h2><p>To illustrate how the two-step aggregate design pattern impacts how we think about and code hyperfunctions, let’s look at the<a href="https://docs.timescale.com/api/latest/hyperfunctions/time-weighted-averages/"> time-weighted average family of functions</a>. (Our<a href="https://timescale.ghost.io/blog/blog/what-time-weighted-averages-are-and-why-you-should-care/"> What Time-Weighted Averages Are and Why You Should Care</a> post provides a lot of context for this next bit, so if you haven’t read it, we recommend doing so. You can also skip this next bit for now.)</p><p>The equation for the time-weighted average is as follows:</p><p>\begin{equation}  time\_weighted\_average = \frac{area\_under\_curve}{ \Delta T}   \end{equation}</p>
<p>As we noted in the <a href="https://timescale.ghost.io/blog/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design-2/#agg-table">table above</a>:</p><ul><li><code>time_weight()</code> is TimescaleDB hyperfunctions’ aggregate and corresponds to the transition function in PostgreSQL’s internal API.</li><li><code>average()</code> is the accessor, which corresponds to the PostgreSQL final function.</li><li><code>rollup()</code> for re-aggregation corresponds to the PostgreSQL combine function.</li></ul><p>The <code>time_weight()</code> function returns an aggregate type that has to be usable by the other functions in the family.</p><p>In this case, we decided on a <code>TimeWeightSummary</code> type that is defined like so (in pseudocode):</p><pre><code class="language-SQL">TimeWeightSummary = (w_sum, first_pt, last_pt)</code></pre><p><code>w_sum</code> is the weighted sum (another name for the area under the curve), and <code>first_pt</code> and <code>last_pt</code> are the first and last (time, value) pairs in the rows that feed into the <code>time_weight()</code> aggregate. </p><p>Here’s a graphic depiction of those elements, which builds on our <a href="https://timescale.ghost.io/blog/blog/what-time-weighted-averages-are-and-why-you-should-care/#mathy-bits-how-to-derive-a-time-weighted-average">how to derive a time-weighted average theoretical description</a>:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/example-graph1-1.jpg" class="kg-image" alt="A graph showing value on the y-axis and time on the x-axis. There are four points:  open parens t 1 comma v 1 close parens, labeled first point to open parens t 4 comma  v 4 close parens, labeled last point. The points are spaced unevenly in time on the graph. The area under the graph is shaded, and labeled w underscore sum. The time axis has a brace describing the total distance between the first and last points labeled Delta T. " loading="lazy" width="692" height="589" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/example-graph1-1.jpg 600w, https://timescale.ghost.io/blog/content/images/2021/08/example-graph1-1.jpg 692w"><figcaption><span style="white-space: pre-wrap;">Depiction of the values we store in the </span><code spellcheck="false" style="white-space: pre-wrap;"><span>TimeWeightSummary</span></code><span style="white-space: pre-wrap;"> representation.</span></figcaption></figure><p></p><p>So, the <code>time_weight()</code> aggregate does all of the calculations as it receives each of the points in our graph and builds a weighted sum for the time period (ΔT) between the first and last points it “sees.” It then outputs the <code>TimeWeightSummary</code>.</p><p>The <code>average()</code> accessor function performs simple calculations to return the time-weighted average from the <code>TimeWeightSummary</code> (in pseudocode where <code>pt.time()</code> returns the time from the point):</p><pre><code class="language-SQL">func average(TimeWeightSummary tws) 
	-&gt; float {
		delta_t = tws.last_pt.time - tws.first_pt.time;
		time_weighted_average = tws.w_sum / delta_t;
		return time_weighted_average;
	}</code></pre><p><br>But, as we built the <code>time_weight</code> hyperfunction, ensuring the <code>rollup()</code> function worked as expected was a little more difficult – and introduced constraints that impacted the design of our <code>TimeWeightSummary</code> data type. </p><p>To understand the rollup function, let’s use our graphical example and imagine the <code>time_weight()</code> function returns two <code>TimeWeightSummaries</code> from different regions of time like so:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/Example-graph-2-1.jpg" class="kg-image" alt="A similar graph to the previous, except that now there are two sets of shaded regions. The first is similar to the previous and is labeled with first sub 1 open parens t 1 comma v 1 close parens, last  1 open parens t 4 comma  v 4 close parens , and w underscore sum  1.  The second is similar, with points first 2 open parens t 5 comma  v 4 close parens and last 2 open parens t 8 comma  v 8 close parens and the label w underscore sum 2 on the shaded portion. " loading="lazy" width="672" height="511" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/Example-graph-2-1.jpg 600w, https://timescale.ghost.io/blog/content/images/2021/08/Example-graph-2-1.jpg 672w"><figcaption><span style="white-space: pre-wrap;">What happens when we have multiple TimeWeightSummaries representing different regions of the graph</span></figcaption></figure><p>The <code>rollup()</code> function needs to take in and return the same <code>TimeWeightSummary</code> data type so that our <code>average()</code> accessor can understand it. (This mirrors how PostgreSQL’s combined function takes in two states from the transition function and then returns a single state for the final function to process.)</p><p>We also want the <code>rollup()</code> output to be the same as if we had computed the <code>time_weight()</code> over all the underlying data. The output should be a <code>TimeWeightSummary</code> representing the full region.  </p><p>The <code>TimeWeightSummary</code> we output should also account for the area in the gap between these two weighted sum states:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/example-graph-3-1.jpg" class="kg-image" alt="A similar picture to the previous, with the area between the points open parens t 4 comma  v 4 close parens aka last 1 and open parens t 5 comma  v 5 close parens aka first 2, down to the time axis highlighted. This is called w underscore sum gap. " loading="lazy" width="663" height="501" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/example-graph-3-1.jpg 600w, https://timescale.ghost.io/blog/content/images/2021/08/example-graph-3-1.jpg 663w"><figcaption><span style="white-space: pre-wrap;">Mind the gap! (between one </span><code spellcheck="false" style="white-space: pre-wrap;"><span>TimeWeightSummary</span></code><span style="white-space: pre-wrap;"> and the next).</span></figcaption></figure><p>The gap area is easy to get because we have the last<sub>1</sub> and first<sub>2</sub> points—and it’s the same as the <code>w_sum</code> we’d get by running the <code>time_weight()</code> aggregate on them.</p><p>Thus, the overall <code>rollup()</code> function needs to do something like this (where <code>w_sum()</code> extracts the weighted sum from the <code>TimeWeightSummary</code>):</p><pre><code class="language-SQL">func rollup(TimeWeightSummary tws1, TimeWeightSummary tws2) 
	-&gt; TimeWeightSummary {
		w_sum_gap = time_weight(tws1.last_pt, tws2.first_pt).w_sum;
		w_sum_total = w_sum_gap + tws1.w_sum + tws2.w_sum;
		return TimeWeightSummary(w_sum_total, tws1.first_pt, tws2.last_pt);
	}
</code></pre><p>Graphically, that means we’d end up with a single <code>TimeWeightSummary</code> representing the whole area:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/example-graph-4-1.jpg" class="kg-image" alt="Similar to the previous graphs, except that now there is only one region that has been shaded, the combined area of the w underscore sum 1, w underscore sum 2, and w underscore sum gap has become one area, w underscore sum. Only the overall first open parens t 1 comma  v 1 close parens and last open parens t 8 comma  v 8 close parens points are shown. " loading="lazy" width="672" height="505" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/example-graph-4-1.jpg 600w, https://timescale.ghost.io/blog/content/images/2021/08/example-graph-4-1.jpg 672w"><figcaption><span style="white-space: pre-wrap;">The combined </span><code spellcheck="false" style="white-space: pre-wrap;"><span>TimeWeightSummary</span></code></figcaption></figure><p>So that’s how the two-step aggregate design approach ends up affecting the real-world implementation of our time-weighted average hyperfunctions. The above explanations are a bit condensed, but they should give you a more concrete look at how <code>time_weight()</code> aggregate, <code>average()</code> accessor, and <code>rollup()</code> functions work.</p><h2 id="summing-it-up">Summing It Up</h2><p>Now that you’ve gotten a tour of the PostgreSQL aggregate API, how it inspired us to make the TimescaleDB hyperfunctions two-step aggregate API, and a few examples of how this works in practice, we hope you'll try it out yourself and tell us what you think :). </p><p>If you're currently dealing with gigantic databases, remember that you can always tier your older, infrequently accessed data to keep things running smoothly without breaking the bank—we built the perfect solution for this with our <a href="https://docs.timescale.com/use-timescale/latest/data-tiering/" rel="noreferrer">Tiered Storage architecture backend</a>. Check it out!</p><p>If you'd like to keep learning about Postgres and its community, visit our <a href="https://www.timescale.com/state-of-postgres/2023" rel="noreferrer"><em>State of PostgreSQL 2023</em> </a>report, which is full of insights on how people around the world use PostgreSQL.</p><p><strong>Going back to hyperfunctions, to get started right away, </strong><a href="https://console.cloud.timescale.com/signup"><strong>spin up a fully managed Timescale service and try it for free</strong></a><strong>. </strong>Hyperfunctions are pre-loaded on each new database service on Timescale, so after you create a new service, you’re all set to use them!</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Postgres Materialized Views, The Timescale Way]]></title>
            <description><![CDATA[Continuous aggregates are one of the most popular features in TimescaleDB, but you can’t fully understand them without some context on PostgreSQL views and materialized views.]]></description>
            <link>https://www.tigerdata.com/blog/materialized-views-the-timescale-way</link>
            <guid isPermaLink="true">https://www.tigerdata.com/blog/materialized-views-the-timescale-way</guid>
            <category><![CDATA[PostgreSQL]]></category>
            <dc:creator><![CDATA[David Kohn]]></dc:creator>
            <pubDate>Thu, 14 Jul 2022 15:34:43 GMT</pubDate>
            <media:content medium="image" href="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_12-1.png">
            </media:content>
            <content:encoded><![CDATA[<h3 id="how-postgresql-views-and-materialized-views-work-and-how-they-influenced-timescaledb-continuous-aggregates"><br>How PostgreSQL Views and Materialized Views Work and How They Influenced TimescaleDB Continuous Aggregates</h3><p>Soon after I graduated from college, I was working on starting a business and moved into a house near campus with five friends. The house was a bit run down, but the rent was cheap, and the people were great. </p><p>I lived there for a couple of years, and we developed a tradition: whenever someone would move out, we would ask them to share three pieces of wisdom with the group. Some were silly, some were serious, some were profound, none seemed remotely related to PostgreSQL or materialized views at the time, but one really has stuck with me. My friend Jason, who’d just finished his Ph.D. in Applied Physics, said the wisdom he’d learned was “Don’t squander your ignorance.” He explained that once you learn something, you end up taking it for granted and it becomes so much harder to overcome your tacit knowledge and ask simple, but important, questions.</p><p>A few months ago, I started a new role managing Engineering Education here at Timescale, and as I’ve started teaching more, Jason’s advice has never been more relevant. Teaching is all about reclaiming squandered ignorance; it’s about constantly remembering what it was like to first learn something, even when you’ve been working on it for years. The things that felt like revelations when we first learned them feel normal as we continue in the field. </p><p>So it’s been common for me that things I’ve worked most closely on can be the hardest to teach. Continuous aggregates are one of the most popular features of TimescaleDB and one of the ones I’m most proud of, partially because I helped design them. </p><p>We were recently working on a <a href="https://timescale.ghost.io/blog/how-we-made-data-aggregation-better-and-faster-on-postgresql-with-timescaledb-2-7/">revamp of continuous aggregates</a>, and as we were discussing the changes, I realized that whenever I’ve explained continuous aggregates, I’ve done it with all of this context about <a href="https://www.tigerdata.com/learn/guide-to-postgresql-views" rel="noreferrer">PostgreSQL views</a> and materialized views in my head.</p><p>I was lucky enough to learn this by trial and error; I had problems that forced me to learn about views and materialized views and figure out all the ways they worked and didn’t work, and I was able to bring that experience to their design when I joined Timescale, but not everyone has that luxury.</p><p><strong>This post is an attempt to distill a few lessons about what views and materialized </strong><a href="https://www.tigerdata.com/learn/guide-to-postgresql-views" rel="noreferrer"><strong>views in PostgreSQL</strong></a><strong> are, what they’re good at, where they fall short, and how we learned from them to make continuous aggregates incredible tools for time-series data analysis. If you need a summary of the main concepts around this topic, </strong><a href="https://www.timescale.com/learn/guide-to-postgresql-views" rel="noreferrer"><strong>check out our Guide on PostgreSQL views</strong></a><strong>.</strong><br><br>This post also comes out of our ongoing <a href="https://www.youtube.com/playlist?list=PLsceB9ac9MHRnmNZrCn_TWkUrCBCPR3mc">Foundations of PostgreSQL and TimescaleDB YouTube series</a>, so please, those of you who are encountering this for the first time, don’t squander your ignorance! Send me questions, no matter how basic they seem—I’d really appreciate it because it will help me become a better teacher. I’ve set up a<a href="https://www.timescale.com/forum/t/ask-your-questions-about-the-views-materialized-views-and-continuous-aggregates-blog-post-here/674"> forum post where you can ask them</a>, or, if you’d prefer, you can ask on our <a href="https://join.slack.com/t/timescaledb/shared_invite/zt-1chdnn3cy-2j_6wpt~TzWUXN6ZygMkbg">Community Slack</a>!</p><h2 id="getting-started-with-views-and-materialized-views">Getting Started With Views and Materialized Views</h2><p>To get an understanding of <a href="https://www.postgresql.org/docs/current/tutorial-views.html" rel="noreferrer">PostgreSQL views</a>, <a href="https://www.postgresql.org/docs/current/rules-materializedviews.html" rel="noreferrer">materialized views</a>, and <a href="https://docs.timescale.com/use-timescale/latest/continuous-aggregates/about-continuous-aggregates/" rel="noreferrer">TimescaleDB continuous aggregates</a>, we’re going to want to have some data to work with to demonstrate the concepts and better understand where each of them is most useful. <br><br>I’ve used the data from our <a href="https://docs.timescale.com/getting-started/latest/#what-is-timescaledb">getting started tutorial</a> so that if you’d like to, you can follow along (you may need to change some of the dates in <code>WHERE</code>clauses, though). Our tutorial deals with financial data, but many of the insights are very broadly applicable. </p><p>Also, I won’t go through the whole thing here, but you should know that we have a <code>company</code> table and a <code>stocks_real_time</code> hypertable, defined like so:</p><pre><code class="language-SQL">CREATE TABLE company (
    symbol text NOT NULL,
    name text NOT NULL
);

CREATE TABLE stocks_real_time (
    time timestamp with time zone NOT NULL,
    symbol text NOT NULL,
    price double precision,
    day_volume integer
);
CREATE INDEX ON stocks_real_time (symbol, time);
SELECT create_hypertable('stocks_real_time', 'time');
</code></pre>
<p>Once you’ve set that up, you can <a href="https://docs.timescale.com/getting-started/latest/add-data/">import data</a>, and you should be able to follow along with the rest if you’d like.</p><h2 id="what-are-postgresql-views-why-should-i-use-them">What Are PostgreSQL Views? Why Should I Use Them?</h2><p>One thing we might want to explore with this dataset is being able to get the name of our company. You’ll note that the <code>name</code> column only exists in the <code>company</code> table, which can be joined to the <code>stocks_real_time</code> table on the <code>symbol</code> column so we can query by either like so:</p><pre><code class="language-SQL">CREATE VIEW stocks_company AS 
SELECT s.symbol, s.price, s.time, s.day_volume, c.name 
FROM stocks_real_time s 
INNER JOIN company c ON s.symbol = c.symbol;
</code></pre>
<p>Once I’ve created a view, I can refer to it in another query:</p><pre><code class="language-SQL">SELECT symbol, price 
FROM stocks_company 
WHERE time &gt;= '2022-04-05' and time &lt;'2022-04-06';
</code></pre>
<p>But what is that actually doing under the hood? As I mentioned before, the view acts as an alias for the stored query, so PostgreSQL replaces the view <code>stocks_company</code> with the query it was defined with and runs the full resulting query. That means the query to the <code>stocks_company</code> view is the same as:</p><pre><code class="language-SQL">SELECT symbol, price 
FROM (
SELECT s.symbol, s.price, s.time, s.day_volume, c.name 
FROM stocks_real_time s 
INNER JOIN company c ON s.symbol = c.symbol) sc 
WHERE time &gt;= '2022-04-05' and time &lt;'2022-04-06';
</code></pre>
<p>We’ve manually replaced the view with the same query that we defined it with. </p><p>How can we tell that they are the same? <a href="https://www.postgresql.org/docs/current/using-explain.html" rel="noreferrer">The <code>EXPLAIN</code>command</a> tells us how PostgreSQL executes a query, and we can use it to see if the query to the view and the query that just runs the query in a subselect produce the same output. </p><p>Note, I know that <code>EXPLAIN</code> plans can initially seem a little intimidating. I’ve tried to make it so you don’t need to know a whole lot about <code>EXPLAIN</code> plans or the like to understand this post, <a href="#what-postgresql-materialized-views-are-and-when-to-use-them" rel="noreferrer">so if you don’t want to read them, feel free to skip over them</a>.</p><p>And if we run both:</p><pre><code class="language-SQL">EXPLAIN (ANALYZE ON, BUFFERS ON) 
SELECT symbol, price 
FROM stocks_company 
WHERE time &gt;= '2022-04-05' and time &lt;'2022-04-06';
--AND
EXPLAIN (ANALYZE ON, BUFFERS ON) 
SELECT symbol, price 
FROM (
SELECT s.symbol, s.price, s.time, s.day_volume, c.name 
FROM stocks_real_time s 
INNER JOIN company c ON s.symbol = c.symbol) sc 
WHERE time &gt;= '2022-04-05' and time &lt;'2022-04-06';
</code></pre>
<p>We can see that they both produce the same query plan (though the timings might be slightly different, they’ll even out with repeated runs).</p><pre><code>Hash Join  (cost=3.68..16328.94 rows=219252 width=12) (actual time=0.110..274.764 rows=437761 loops=1)
   Hash Cond: (s.symbol = c.symbol)
   Buffers: shared hit=3667
   -&gt;  Index Scan using _hyper_5_2655_chunk_stocks_real_time_time_idx on _hyper_5_2655_chunk s  (cost=0.43..12488.79 rows=438503 width=12) (actual time=0.057..125.607 rows=437761 loops=1)
         Index Cond: (("time" &gt;= '2022-04-05 00:00:00+00'::timestamp with time zone) AND ("time" &lt; '2022-04-06 00:00:00+00'::timestamp with time zone))
         Buffers: shared hit=3666
   -&gt;  Hash  (cost=2.00..2.00 rows=100 width=4) (actual time=0.034..0.035 rows=100 loops=1)
         Buckets: 1024  Batches: 1  Memory Usage: 12kB
         Buffers: shared hit=1
         -&gt;  Seq Scan on company c  (cost=0.00..2.00 rows=100 width=4) (actual time=0.006..0.014 rows=100 loops=1)
               Buffers: shared hit=1
 Planning:
   Buffers: shared hit=682
 Planning Time: 1.807 ms
 Execution Time: 290.851 ms
(15 rows)
</code></pre>
<p>The plan joins the <code>company</code> to the relevant chunk of the <code>stocks_real_time</code> hypertable and uses an index scan to fetch the right rows. But you don’t really need to understand exactly what’s going on here to understand that they’re doing the same thing.</p><div class="kg-card kg-callout-card kg-callout-card-grey"><div class="kg-callout-emoji">✨</div><div class="kg-callout-text"><b><strong style="white-space: pre-wrap;">Editor's Note: </strong></b>If you’d like to learn more about EXPLAIN, I recommend taking a look at the <a href="https://www.youtube.com/watch?v=UUcVS0290nY&amp;list=PLsceB9ac9MHRnmNZrCn_TWkUrCBCPR3mc&amp;index=8">Explaining Explain session</a> that my colleague Feike Steenbergen gave a couple of weeks ago. It was awesome!</div></div><h3 id="views-hide-complexity">Views hide complexity</h3><p>The <code>JOIN</code> in our view is very simple, which means the aliased query is relatively simple, but you can imagine that as the views get more complex, it can be very helpful to have a much simpler way for a user to query the database, where they don’t have to write all the <code>JOINs</code> themselves. (You can also use special views like <a href="https://www.2ndquadrant.com/en/blog/how-do-postgresql-security_barrier-views-work/">security barrier views to grant access to data securely</a>, but that’s more than we can cover here!).</p><p>Unfortunately, hiding the complexity can also be a problem. For instance, you may or may not have noticed in our example that we <em>don’t actually need the <code>JOIN</code>!</em> The <code>JOIN</code> gets us the <code>name</code> column from the <code>company</code> table, but we’re only selecting the <code>symbol</code> and <code>price</code> columns, which come from the <code>stocks_real_time</code> table! If we run the query directly on the table, it can go about twice as  fast by avoiding the <code>JOIN</code>:</p><pre><code>Index Scan using _hyper_5_2655_chunk_stocks_real_time_time_idx on _hyper_5_2655_chunk  (cost=0.43..12488.79 rows=438503 width=12) (actual time=0.021..72.770 rows=437761 loops=1)
  Index Cond: (("time" &gt;= '2022-04-05 00:00:00+00'::timestamp with time zone) AND ("time" &lt; '2022-04-06 00:00:00+00'::timestamp with time zone))
  Buffers: shared hit=3666
Planning:
  Buffers: shared hit=10
Planning Time: 0.243 ms
Execution Time: 140.775 ms
</code></pre>
<p>If I’d written out the query, I might have seen that I didn’t need the <code>JOIN</code> (or never written it in the first place). Whereas the view hides that complexity. So they can make things easier, but that can lead to performance pitfalls if we’re not careful. </p><p>If we actually <code>SELECT</code> the <code>name</code> column, then we could say we’re using the view more for what it was meant for like so:</p><pre><code class="language-SQL">SELECT name, price, symbol 
FROM stocks_company 
WHERE time &gt;= '2022-04-05' AND time &lt;'2022-04-06';
</code></pre>
<p>So to sum up this section on views: </p><ul><li>Views are a way to store an alias for a query in the database.</li><li>PostgreSQL will replace the view name with the query you use in the view definition. </li></ul><p>Views can be good for reducing complexity for the user, so they don’t have to write out complex <code>JOINs</code>, but can also lead to performance problems if they are overused and because hiding the complexity can make it harder to identify potential performance pitfalls. </p><p>One thing you’ll notice is that <strong>views can improve the user interface, but they won’t really ever improve performance</strong>, because they don’t actually run the query, they just alias it. If you want something that runs the query, you’ll need a materialized view.</p><h2 id="what-postgresql-materialized-views-are-and-when-to-use-them">What PostgreSQL Materialized Views Are and When to Use Them</h2><p>When I <a href="https://www.postgresql.org/docs/current/sql-creatematerializedview.html">create a materialized view</a>, it actually runs the query and stores the results. In essence, this means the materialized view acts as a <a href="https://en.wikipedia.org/wiki/Cache_(computing)">cache</a> for the query. Caching is a common way to improve performance in all sorts of computing systems. The question we might ask is: will it be helpful here? So let’s try it out and see how it goes. <br><br><a href="https://www.postgresqltutorial.com/postgresql-views/postgresql-materialized-views/" rel="noreferrer">Creating a materialized view</a> is quite easy, I can just add the <code>MATERIALIZED</code> keyword to my create view command:</p><pre><code class="language-SQL">CREATE MATERIALIZED VIEW stocks_company_mat AS 
SELECT s.symbol, s.price, s.time, s.day_volume, c.name 
FROM stocks_real_time s INNER JOIN company c ON s.symbol = c.symbol;

CREATE INDEX on stocks_company_mat (symbol, time DESC);
CREATE INDEX on stocks_company_mat (time DESC);
</code></pre>
<p>You’ll also notice that I created some indexes on the materialized view (the same ones I have on <code>stocks_real_time</code>)! That’s one of the cool things about materialized views, you can create indexes on them because under the hood they’re just tables that store the results of a query (we’ll explain that more later). </p><p>Now I can run <a href="https://www.cybertec-postgresql.com/en/how-to-interpret-postgresql-explain-analyze-output/" rel="noreferrer"><code>EXPLAIN ANALYZE</code></a> on a slightly different query, where I’m trying to get the data for ‘AAPL’ for four days on both to understand how much this caching helps our query:</p><pre><code class="language-SQL">EXPLAIN (ANALYZE ON, BUFFERS ON) SELECT name, price FROM stocks_company_mat WHERE time &gt;= '2022-04-05' AND time &lt;'2022-04-09' AND symbol = 'AAPL';
Bitmap Heap Scan on stocks_company_mat  (cost=1494.93..56510.51 rows=92196 width=17) (actual time=11.796..46.336 rows=95497 loops=1)
  Recheck Cond: ((symbol = 'AAPL'::text) AND ("time" &gt;= '2022-04-05 00:00:00+00'::timestamp with time zone) AND ("time" &lt; '2022-04-09 00:00:00+00'::timestamp with time zone))
  Heap Blocks: exact=14632
  Buffers: shared hit=14969
  -&gt;  Bitmap Index Scan on stocks_company_mat_symbol_time_idx  (cost=0.00..1471.88 rows=92196 width=0) (actual time=9.456..9.456 rows=95497 loops=1)
        Index Cond: ((symbol = 'AAPL'::text) AND ("time" &gt;= '2022-04-05 00:00:00+00'::timestamp with time zone) AND ("time" &lt; '2022-04-09 00:00:00+00'::timestamp with time zone))
        Buffers: shared hit=337
Planning:
  Buffers: shared hit=5
Planning Time: 0.102 ms
Execution Time: 49.995 ms

EXPLAIN (ANALYZE ON, BUFFERS ON) SELECT name, price FROM stocks_company WHERE time &gt;= '2022-04-05' AND time &lt;'2022-04-09' AND symbol = 'AAPL';
Nested Loop  (cost=919.95..30791.92 rows=96944 width=19) (actual time=6.023..75.367 rows=95497 loops=1)
  Buffers: shared hit=13215
  -&gt;  Seq Scan on company c  (cost=0.00..2.25 rows=1 width=15) (actual time=0.006..0.018 rows=1 loops=1)
        Filter: (symbol = 'AAPL'::text)
        Rows Removed by Filter: 99
        Buffers: shared hit=1
  -&gt;  Append  (cost=919.95..29820.23 rows=96944 width=12) (actual time=6.013..67.491 rows=95497 loops=1)
        Buffers: shared hit=13214
        -&gt;  Bitmap Heap Scan on _hyper_5_2655_chunk s_1  (cost=919.95..11488.49 rows=49688 width=12) (actual time=6.013..22.334 rows=49224 loops=1)
              Recheck Cond: ((symbol = 'AAPL'::text) AND ("time" &gt;= '2022-04-05 00:00:00+00'::timestamp with time zone) AND ("time" &lt; '2022-04-09 00:00:00+00'::timestamp with time zone))
              Heap Blocks: exact=6583
              Buffers: shared hit=6895
(... elided for space)
Planning:
  Buffers: shared hit=30
Planning Time: 0.465 ms
Execution Time: 78.932 ms
</code></pre>
<p>Taking a look at these plans, we can see that it helps less than one might think! It sped it up a little, but really, they’re doing almost the same amount of work! How can I tell? Well, they scan approximately the same number of 8KB buffers (see <a href="https://www.youtube.com/watch?v=JOrXRsES3mk&amp;list=PLsceB9ac9MHRnmNZrCn_TWkUrCBCPR3mc&amp;index=1">Lesson 0 of the Foundations series</a> to learn more about those), and they scan the same number of rows.</p><h3 id="when-materialized-view-performance-doesnt-materialize">When materialized view performance doesn't materialize</h3><p>Why is this? Well, our <code>JOIN</code> didn’t reduce the number of rows in the query, so the materialized view <code>stocks_company_mat</code> actually has the same number of rows in it as the <code>stocks_real_time</code> hypertable!</p><pre><code class="language-SQL">SELECT 
(SELECT count(*) FROM stocks_company_mat) as rows_mat, 
(SELECT count(*) FROM stocks_real_time) as rows_tab;

 rows_mat | rows_tab 
----------+----------
  7375355 |  7375355

</code></pre>
<p>So, not a huge benefit, and <em>we have to store the same number of rows over again</em>. So we’re getting little benefit for a pretty large cost in terms of how much storage we have to use. Now this could have been a large benefit if we were running a very expensive function or doing a very complex <code>JOIN</code> in our materialized view definition, but we’re not, so this doesn’t save us much. </p><p>The thing about our example is that it only gets worse from here. One of the things we might want to do with our view or materialized view is being able to use a <a href="https://www.geeksforgeeks.org/postgresql-where-clause/" rel="noreferrer"><code>WHERE</code></a> clause to filter not just on <code>symbol</code> but on the company <code>name</code>. (Maybe I don’t remember the stock symbol for a company, but I do remember its name.) Remember that the <code>name</code> column is the one we joined on, so let’s run that query on both the view and materialized view and see what happens:</p><pre><code class="language-SQL">
EXPLAIN (ANALYZE ON, BUFFERS ON) SELECT name, price from stocks_company_mat WHERE time &gt;= '2022-04-05' and time &lt;'2022-04-06' AND name = 'Apple' ;
Index Scan using stocks_company_mat_time_idx on stocks_company_mat  (cost=0.43..57619.99 rows=92196 width=17) (actual time=0.022..605.268 rows=95497 loops=1)
  Index Cond: (("time" &gt;= '2022-04-05 00:00:00+00'::timestamp with time zone) AND ("time" &lt; '2022-04-09 00:00:00+00'::timestamp with time zone))
  Filter: (name = 'Apple'::text)
  Rows Removed by Filter: 1655717
  Buffers: shared hit=112577
Planning:
  Buffers: shared hit=3
Planning Time: 0.116 ms
Execution Time: 609.040 ms

EXPLAIN (ANALYZE ON, BUFFERS ON) SELECT name, price from stocks_company WHERE time &gt;= '2022-04-05' and time &lt;'2022-04-06' AND name = 'Apple' ;
Nested Loop  (cost=325.22..21879.02 rows=8736 width=19) (actual time=5.642..56.062 rows=95497 loops=1)
  Buffers: shared hit=13215
  -&gt;  Seq Scan on company c  (cost=0.00..2.25 rows=1 width=15) (actual time=0.007..0.018 rows=1 loops=1)
        Filter: (name = 'Apple'::text)
        Rows Removed by Filter: 99
        Buffers: shared hit=1
  -&gt;  Append  (cost=325.22..21540.78 rows=33599 width=12) (actual time=5.633..48.232 rows=95497 loops=1)
        Buffers: shared hit=13214
        -&gt;  Bitmap Heap Scan on _hyper_5_2655_chunk s_1  (cost=325.22..9866.59 rows=17537 width=12) (actual time=5.631..21.713 rows=49224 loops=1)
              Recheck Cond: ((symbol = c.symbol) AND ("time" &gt;= '2022-04-05 00:00:00+00'::timestamp with time zone) AND ("time" &lt; '2022-04-09 00:00:00+00'::timestamp with time zone))
              Heap Blocks: exact=6583
              Buffers: shared hit=6895
…
Planning:
  Buffers: shared hit=30
Planning Time: 0.454 ms
Execution Time: 59.558 ms
</code></pre>
<p>This time, my query on the regular view is much better! It hits far fewer buffers and returns 10x faster! This is because we created an index on <code>(symbol, time DESC)</code> for the materialized view, but not on <code>(name, time DESC)</code>, so it has to fall back to scanning the full <code>time</code>index and removing the rows that don’t match. </p><p>The normal view, however, can use the more selective <code>(symbol, time DESC)</code> on the <code>stocks_real_time</code> hypertable because it’s performing the <code>JOIN</code> to the <code>company</code> table, and it joins on the <code>symbol</code> column, which means it can still use the more selective index. We “enhanced” the materialized view by performing the <code>JOIN</code> and caching the results, but then we’d need to create an index on the joined column too. <br><br>So we’re learning that this query isn’t a great candidate for a materialized view, because it’s not a crazy complex time-consuming <code>JOIN</code> and doesn’t reduce the number of rows. But if we had a query that we wanted to run that would reduce the number of rows, then that would be a great candidate for a materialized view.</p><h3 id="when-materialized-views-perform-well">When materialized views perform well</h3><p>As it turns out, there’s a very common set of queries on stock data like this that does reduce the number of rows, they’re called <strong>O</strong>pen-<strong>H</strong>igh-<strong>L</strong>ow-<strong>C</strong>lose queries (OHLC), and they look something like this:</p><pre><code class="language-SQL">CREATE VIEW ohlc_view AS 
SELECT time_bucket('15 min', time) bucket, symbol, first(price, time), max(price), min(price), last(price, time) 
FROM stocks_real_time 
WHERE time &gt;= '2022-04-05' and time &lt;'2022-04-06' 
GROUP BY time_bucket('15 min', time), symbol;

CREATE MATERIALIZED VIEW ohlc_mat AS 
SELECT time_bucket('15 min', time) bucket, symbol, first(price, time), max(price), min(price), last(price, time) 
FROM stocks_real_time 
GROUP BY time_bucket('15 min', time), symbol ;

CREATE INDEX on ohlc_mat(symbol, bucket);
CREATE INDEX ON ohlc_mat(bucket);
</code></pre>
<p>Here I’m aggregating a lot of rows together, so I end up storing a lot fewer in my materialized view. (The view doesn’t store any rows, it’s just an alias for the query.) I still created a few indexes to help speed lookups, but they’re much smaller as well because there are many fewer rows in the output of this query. So now, if I select from the normal view and the materialized view, I see a huge speedup!<br><br>Normal view:</p><pre><code class="language-SQL">EXPLAIN (ANALYZE ON, BUFFERS ON) 
SELECT  bucket, symbol, first, max, min, last 
FROM ohlc_view
WHERE bucket &gt;= '2022-04-05' AND bucket &lt;'2022-04-06';
Finalize GroupAggregate  (cost=39098.81..40698.81 rows=40000 width=44) (actual time=875.233..1000.171 rows=3112 loops=1)
  Group Key: (time_bucket('00:15:00'::interval, _hyper_5_2655_chunk."time")), _hyper_5_2655_chunk.symbol
  Buffers: shared hit=4133, temp read=2343 written=6433
  -&gt;  Sort  (cost=39098.81..39198.81 rows=40000 width=92) (actual time=875.212..906.810 rows=5151 loops=1)
        Sort Key: (time_bucket('00:15:00'::interval, _hyper_5_2655_chunk."time")), _hyper_5_2655_chunk.symbol
        Sort Method: quicksort  Memory: 1561kB
        Buffers: shared hit=4133, temp read=2343 written=6433
        -&gt;  Gather  (cost=27814.70..36041.26 rows=40000 width=92) (actual time=491.920..902.094 rows=5151 loops=1)
              Workers Planned: 1
              Workers Launched: 1
              Buffers: shared hit=4133, temp read=2343 written=6433
              -&gt;  Partial HashAggregate  (cost=26814.70..31041.26 rows=40000 width=92) (actual time=526.663..730.168 rows=2576 loops=2)
                    Group Key: time_bucket('00:15:00'::interval, _hyper_5_2655_chunk."time"), _hyper_5_2655_chunk.symbol
                    Planned Partitions: 128  Batches: 129  Memory Usage: 1577kB  Disk Usage: 19592kB
                    Buffers: shared hit=4133, temp read=2343 written=6433
                    Worker 0:  Batches: 129  Memory Usage: 1577kB  Disk Usage: 14088kB
                    -&gt;  Result  (cost=0.43..13907.47 rows=257943 width=28) (actual time=0.026..277.314 rows=218880 loops=2)
                          Buffers: shared hit=4060
                          -&gt;  Parallel Index Scan using _hyper_5_2655_chunk_stocks_real_time_time_idx on _hyper_5_2655_chunk  (cost=0.43..10683.19 rows=257943 width=20) (actual time=0.025..176.330 rows=218880 loops=2)
                                Index Cond: (("time" &gt;= '2022-04-05 00:00:00+00'::timestamp with time zone) AND ("time" &lt; '2022-04-06 00:00:00+00'::timestamp with time zone))
                                Buffers: shared hit=4060
Planning:
  Buffers: shared hit=10
Planning Time: 0.615 ms
Execution Time: 1003.425 ms
</code></pre>
<p>Materialized view:</p><pre><code class="language-SQL">EXPLAIN (ANALYZE ON, BUFFERS ON) 
SELECT  bucket, symbol, first, max, min, last 
FROM ohlc_mat 
WHERE bucket &gt;= '2022-04-05' AND bucket &lt;'2022-04-06';
Index Scan using ohlc_mat_bucket_idx on ohlc_mat  (cost=0.29..96.21 rows=3126 width=43) (actual time=0.009..0.396 rows=3112 loops=1)
  Index Cond: ((bucket &gt;= '2022-04-05 00:00:00+00'::timestamp with time zone) AND (bucket &lt; '2022-04-06 00:00:00+00'::timestamp with time zone))
  Buffers: shared hit=35
Planning:
  Buffers: shared hit=6
Planning Time: 0.148 ms
Execution Time: 0.545 ms
</code></pre>
<p>Well, that helped! We hit far fewer buffers and scanned far fewer rows with the materialized case, and we didn’t need to perform the <a href="https://www.tutorialspoint.com/postgresql/postgresql_group_by.htm" rel="noreferrer"><code>GROUP BY</code></a> and aggregate, which removes a sort, etc. All of that means that we sped up our query dramatically! But, it’s not rainbows and butterflies for materialized views. Because we didn’t cover one of their big problems, they get out of date!<br><br>So, if you think about a table like our stocks table, it’s a typical time-series use case which means it looks something like this:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_1.png" class="kg-image" alt="" loading="lazy" width="1526" height="1096" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_1.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_1.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_1.png 1526w" sizes="(min-width: 720px) 720px"></figure><p><br>We have a materialized view that we created, and it has been populated at a certain time with our query.</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_2.png" class="kg-image" alt="" loading="lazy" width="1526" height="1214" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_2.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_2.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_2.png 1526w" sizes="(min-width: 720px) 720px"></figure><p><br>But then, as time passes, and we’re, say, 15 minutes later, and we’ve inserted more data, the view is out of date! We’re <code>time_bucket</code>ing by 15-minute increments, so there’s a whole set of buckets that we don’t have! </p><p>Essentially, materialized views are only as accurate as the last time they ran the query they are caching. You need to run <a href="https://www.postgresql.org/docs/current/sql-refreshmaterializedview.html" rel="noreferrer"><code>REFRESH MATERIALIZED VIEW</code></a>  to ensure they are up to date. </p><p>Once you run <code>REFRESH MATERIALIZED VIEW</code>, we’ll end up with the new data in our materialized view, like so:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_3.png" class="kg-image" alt="" loading="lazy" width="1526" height="1214" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_3.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_3.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_3.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>The thing is, <code>REFRESH</code>ing a view can be expensive, and to understand why we should understand a bit more about how they work and why they get out of date. And that can be expensive.</p><h2 id="how-materialized-views-work-and-why-they-get-out-of-date">How Materialized Views Work (and Why They Get Out of Date)</h2><p>To understand how <a href="https://www.postgresqltutorial.com/postgresql-views/postgresql-materialized-views/" rel="noreferrer">materialized views</a> get out of date and what refresh is doing, it helps to understand a little about how they work under the hood. Essentially, when you create a materialized view, you are creating a table and populating it with the data from the query. For the <code>ohlc_mat</code> view we’ve been working with, it’s equivalent to:</p><pre><code class="language-SQL">CREATE TABLE ohlc_tab AS 
SELECT time_bucket('15 min', time) bucket, symbol, first(price, time), max(price), min(price), last(price, time) 
FROM stocks_real_time 
GROUP BY time_bucket('15 min', time), symbol;
</code></pre>
<p>Now, what happens when I insert data into the underlying table?</p><p>So, our materialized view <code>ohlc_mat</code> is storing the results of the query run when we created it.</p><pre><code class="language-SQL">INSERT INTO stocks_real_time VALUES (now(), 'AAPL', 170.91, NULL);
</code></pre>
<figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_4.png" class="kg-image" alt="" loading="lazy" width="1526" height="1214" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_4.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_4.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_4.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>The regular view (<code>ohlc_view</code>) will stay up to date because it’s just running the queries directly on the raw data in <code>stocks_real_time</code>. And if we’re only inserting data close to <code>now()</code>, and only querying much older data, then the materialized view will seem like it’s okay. We’ll see no change for our query from a month or two ago, but if we try to query a more recent time, we won’t have any data. If we want it up to date with more recent data, we’ll need to run:</p><pre><code class="language-SQL">REFRESH MATERIALIZED VIEW ohlc_mat;
</code></pre>
<p>When we do this, what is actually happening under the hood is that we truncate (remove all the data) from the table, and then run the query again and insert it into the table.</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_5.png" class="kg-image" alt="" loading="lazy" width="1526" height="1214" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_5.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_5.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_5.png 1526w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_6.png" class="kg-image" alt="" loading="lazy" width="1526" height="1214" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_6.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_6.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_6.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>If we were using the <code>ohlc_tab</code> table from above, the equivalent operations would be something like:</p><pre><code class="language-SQL">TRUNCATE TABLE ohlc_tab;

INSERT INTO ohlc_tab 
SELECT time_bucket('15 min', time) bucket, symbol, first(price, time), max(price), min(price), last(price, time) 
FROM stocks_real_time 
GROUP BY time_bucket('15 min', time), symbol;
</code></pre>
<p>(This works slightly differently when you run <code>REFRESH MATERIALIZED VIEW</code> with the <code>CONCURRENTLY</code> option, but fundamentally, it always runs the query over the entire data set, and getting into the details is beyond the scope of this post.)</p><p>The database, much like with a view, stores the query we ran so that when we run our <code>REFRESH</code> it just knows what to do, which is great, but it’s not the most efficient. Even though most of the data didn’t change, we still threw out the whole data set, and re-run the whole query. </p><p>While that might be okay when you’re working with, say <a href="https://www.tigerdata.com/learn/understanding-oltp" rel="noreferrer">OLTP</a> data that PostgreSQL works with, and your updates/deletes are randomly spread around your data set, it starts to seem pretty inefficient when you’re working with time-series data, where the writes are mostly in the most recent period. </p><p>So, to sum up, we found a case where the materialized view really helps us because the output from the query is so much smaller than the number of rows we have to scan to calculate it. In our case, it was an aggregate. But we also noticed that, when we used a materialized view, the data gets out of date because we’re storing the output of the query, rather than rerunning it at query time as you do with a view.</p><p>In order to get the materialized view to be up to date, we learned that we need to <code>REFRESH</code> it, but for time-series use cases, a) you have to refresh it frequently (in our case, approximately every 15 minutes or so at least) for it to be up to date, and b) the refresh is inefficient because we have to delete and re-materialize all the data, maybe going back months, to get the new information from just the previous 15 minutes. <strong>And that’s one of the main reasons we developed continuous aggregates at Timescale.</strong></p><h2 id="what-are-continuous-aggregates-why-should-i-use-them">What Are Continuous Aggregates? Why Should I Use Them?</h2><p><a href="https://docs.timescale.com/use-timescale/latest/continuous-aggregates/about-continuous-aggregates/#about-continuous-aggregates"><u>Continuous aggregates</u></a> function as incremental, automatically updated materialized views. They scan and update the results of your query in the background, ensuring that new data is incorporated and old data is adjusted based on your refresh policy. <a href="https://timescale.ghost.io/blog/continuous-aggregates-faster-queries-with-automatically-maintained-materialized-views/"><u>Check out an example here.</u></a> Keep in mind that this does not prevent you from retrieving data typically.</p><p>During a refresh, only the data that has changed since the last refresh is updated. This eliminates the need to rerun the entire query to retrieve data that you already have. This is also known as real-time aggregation; all continuous aggregates use real-time aggregation.</p><h3 id="real-time-aggregates">Real-time aggregates</h3><p><a href="https://docs.timescale.com/use-timescale/latest/continuous-aggregates/real-time-aggregates/"><u>Real-time aggregates</u></a> address the problem of maintaining the most current data using continuous aggregates. Here's an example: if you have a 15-minute refresh policy and the last refresh occurred five minutes ago, there's already a gap in your data. Real-time aggregation tackles this by filling this gap with the latest raw data from your table. Real-time aggregation extracts the most recent yet-to-be-materialized raw data from the source table or view and adds it to the recently retrieved raw data from your table or view. This gives you an up-to-date view of your data for <a href="https://www.timescale.com/learn/real-time-analytics-in-postgres"><u>real-time analytics</u></a>. <br></p><h2 id="how-continuous-aggregates-work-and-how-they-were-inspired-by-the-best-of-views-and-materialized-views"><strong>How Continuous Aggregates Work and How They Were Inspired by the Best of Views and Materialized Views</strong></h2><p>We’ll build up to how exactly continuous aggregates work in this section, piece by piece.</p><p>Fundamentally, when we create a continuous aggregate, we’re doing something very similar to what happens when we create a materialized view. That’s why we use a slightly modified version of the interface for creating a materialized view:</p><pre><code class="language-SQL">CREATE MATERIALIZED VIEW ohlc_cont 
WITH (timescaledb.continuous) AS 
SELECT time_bucket('15 min', time) bucket, symbol, first(price, time), max(price), min(price), last(price, time) 
FROM stocks_real_time 
GROUP BY time_bucket('15 min', time), symbol;
</code></pre>
<p>Once we’ve done that, we end up in a very similar situation to what we have with a materialized view. We have the data that was around when created the view, but as new data gets inserted, the view will get out of date.<strong> </strong><br></p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_6_5-1.png" class="kg-image" alt="" loading="lazy" width="1526" height="1214" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_6_5-1.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_6_5-1.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_6_5-1.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>In order to keep a continuous aggregate up to date, we need a scheduled aggregation.</p><h3 id="scheduled-aggregation-of-new-data">Scheduled aggregation of new data</h3><p>We saw two main problems with materialized views that we wanted to address with scheduled aggregations:</p><ol><li>We have to manually refresh a materialized view when we want it to remain up to date.</li><li>We don’t want to re-run the query on all the old data unnecessarily; we should only run it on the new data. </li></ol><p>To schedule aggregations, we need to create a continuous aggregate policy:</p><pre><code class="language-SQL">SELECT add_continuous_aggregate_policy('ohlc_cont'::regclass, start_offset=&gt;NULL, end_offset=&gt;'15 mins'::interval,  schedule_interval=&gt;'5 mins'::interval);
</code></pre>
<p>Once we’ve scheduled a continuous aggregate policy, it will run automatically according to the <code>schedule_interval</code> we’ve specified. In our case, it runs every five minutes. When it runs, it looks at the data we’ve already materialized and the new inserts and looks to see if we’ve finished at least one 15-minute bucket. If we have, it will run the query on just that next 15-minute portion and materialize the results in our continuous aggregate.</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_7.png" class="kg-image" alt="" loading="lazy" width="1526" height="1214" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_7.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_7.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_7.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>This means that the continuous aggregate now automatically has data from the next 15-minute period without user intervention. </p><p>And it was much more efficient. Unlike running <code>REFRESH MATERIALIZED VIEW</code>, we didn’t drop all the old data and recompute the aggregate against it, we just ran the aggregate query against the next 15-minute period and added that to our materialization. And as we move forward in time, this can keep occurring as each successive 15-minute period (or whatever period we chose for the <code>time_bucket</code> in the continuous aggregate definition) gets filled in with new data and then materialized. </p><p>One thing to note about this is that we keep track of where we’ve materialized up to by storing what we call a watermark, represented here by the dotted line. (<strong>NB</strong>: It’s named after the high watermark caused by a flood, not the watermark on a bank check.) So before the scheduled aggregation runs, the watermark is right after all the data we’ve materialized:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_8.png" class="kg-image" alt="" loading="lazy" width="1526" height="1246" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_8.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_8.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_8.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>That helps us locate our next bucket and ensure it’s all there before we run the aggregation. Once we have, we move the watermark:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_9-1.png" class="kg-image" alt="" loading="lazy" width="1526" height="1312" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_9-1.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_9-1.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_9-1.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>So our watermark represents the furthest point we’ve materialized up until now.</p><p>But, you might notice that our continuous aggregates still aren’t fully up to date and wouldn’t give us the same results as a view that ran the same query. Why?</p><ol><li>Scheduled aggregates will have some gap between when the next bucket has all of its data and when the job runs to materialize it.</li><li>We only materialize data once the next bucket is full by default, so we’re missing the partial bucket where inserts are happening right now. We might want to get partial results for that bucket (this is especially true when we’re using larger buckets).</li></ol><p>To address this, we made real-time views.</p><h3 id="real-time-views">Real-time views</h3><p>Real-time views combine the best of materialized views and normal views to give us a more up-to-date view of our data. They’re the default for continuous aggregates, so I don’t need to change how I made my continuous aggregate at all. However, I will admit that I elided a few things in the previous picture about how continuous aggregates work under the hood.</p><p>Real-time continuous aggregates have two parts:</p><ol><li>A <em>materialized hypertable</em>, where our already computed aggregates are stored.</li><li>And a <em>real-time view, </em>which queries both the materialized <a href="https://www.tigerdata.com/blog/database-indexes-in-postgresql-and-timescale-cloud-your-questions-answered" rel="noreferrer">hypertable</a> and the raw hypertable (in the not-yet-aggregated region) and combines the results together.</li></ol><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_10.png" class="kg-image" alt="" loading="lazy" width="1526" height="1892" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_10.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_10.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_10.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>So, if you look at the view definition of the continuous aggregate, it looks like this:</p><pre><code class="language-SQL">CREATE VIEW ohlc_cont AS  SELECT _materialized_hypertable_15.bucket,
    _materialized_hypertable_15.symbol,
    _materialized_hypertable_15.first,
    _materialized_hypertable_15.max,
    _materialized_hypertable_15.min,
    _materialized_hypertable_15.last
   FROM _timescaledb_internal._materialized_hypertable_15
  WHERE _materialized_hypertable_15.bucket &lt; COALESCE(_timescaledb_internal.to_timestamp(_timescaledb_internal.cagg_watermark(15)), '-infinity'::timestamp with time zone)
UNION ALL
 SELECT time_bucket('00:15:00'::interval, stocks_real_time."time") AS bucket,
    stocks_real_time.symbol,
    first(stocks_real_time."time", stocks_real_time.price) AS first,
    max(stocks_real_time.price) AS max,
    min(stocks_real_time.price) AS min,
    last(stocks_real_time."time", stocks_real_time.price) AS last
   FROM stocks_real_time
  WHERE stocks_real_time."time" &gt;= COALESCE(_timescaledb_internal.to_timestamp(_timescaledb_internal.cagg_watermark(15)), '-infinity'::timestamp with time zone)
  GROUP BY (time_bucket('00:15:00'::interval, stocks_real_time."time")), stocks_real_time.symbol;
</code></pre>
<p>It’s two queries put together with a <a href="https://www.postgresql.org/docs/current/queries-union.html"><code>UNION ALL</code></a>, the first just selecting the data straight out of the materialized hypertable where our bucket is below the watermark, the second running the aggregation query where our time column is above the watermark. </p><p>So you can see how this takes advantage of the best of both materialized views and normal views to create something that is much faster than a normal view but still up to date! </p><p>It’s not going to be as performant as just querying the already materialized data (though we do have an <a href="https://docs.timescale.com/getting-started/latest/create-cagg/create-cagg-policy/">option to allow you to do that if you want to</a>), but for most users, the last few months or even years of data is already materialized whereas only the last few minutes or days of raw data needs to be queried, so that still creates a huge speedup!</p><h3 id="invalidation-of-out-of-order-data">Invalidation of out-of-order data</h3><p>You may have noticed that I was making a big assumption in all of my diagrams. I was assuming that <em>all</em> of our inserts happen in the most recent time period. For time-series workloads, this is <em>mostly</em> true. <em>Most</em> data comes in time order. But, most and all are <em>very</em> different things. Especially with time-series workloads, where we have so much data coming in, that even if 99 percent of the data is in time order, 1 percent of the data is still a lot!</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_11-1.png" class="kg-image" alt="" loading="lazy" width="1526" height="1210" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_11-1.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_11-1.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_11-1.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>And the results of the aggregate would be wrong by a meaningful amount if we simply let the inserts (or updates or deletes) build up over time. This cache invalidation problem is a very common problem in computing and a very hard one! PostgreSQL materialized views solve this problem by dropping all the old data and re-materializing it every time, but we already said how inefficient that was. </p><p>The other way that many folks try to solve this sort of problem in a database like PostgreSQL is a trigger. A standard trigger would run for every row and update the aggregates for every row.</p><p>But in practice, it’s hard to get a per-row trigger to work very well, and it still would cause significant <em>write amplification</em>, meaning, we’d have to write multiple times for every row we insert. </p><p>In fact, we’d need to write at least once for each row for each continuous aggregate we had on the raw hypertable. It would also limit the aggregates we can use to those that can be modified by a trigger, which are fewer than we might like. <br><br>So instead, we created a special kind of trigger that tracks the minimum and maximum <em>times</em> modified across all the rows in a statement and writes out the range of times that were modified to a log table. We call that an invalidation log.</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_12.png" class="kg-image" alt="" loading="lazy" width="1526" height="1258" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_12.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_12.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_12.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>The next time the continuous aggregate job runs, it has to do two things: it runs the normal aggregation of the next 15 minutes of data, and it runs an aggregation over each of the invalidated regions to recalculate the proper value over that period.</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_13.png" class="kg-image" alt="" loading="lazy" width="1526" height="1312" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_13.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_13.png 1000w, https://timescale.ghost.io/blog/content/images/2022/07/20220711_Materialized-views-and-CAGGS_Diagram_13.png 1526w" sizes="(min-width: 720px) 720px"></figure><p>Note that this makes our continuous aggregates <a href="https://en.wikipedia.org/wiki/Eventual_consistency">eventually consistent</a> for out-of-order modifications. However, real-time views make continuous aggregates more strongly consistent for recent data (because they use a view under the hood). </p><p><br><br>While we could make more strongly consistent aggregates by joining to our log table and rerunning the aggregation in real time for the invalidated regions, we talked to users and decided that eventual consistency was good enough for most cases here. After all, this data is already late coming in. Essentially, we think the performance impact of doing that wasn’t worth the consistency guarantees. And anyway, if ever a user wants to, they can trigger a manual refresh of the continuous aggregate for the modified region by running the <a href="https://docs.timescale.com/api/latest/continuous-aggregates/refresh_continuous_aggregate/">manual <code>refresh_continuous_aggregates</code> procedure</a>, which updates the data in the materialized hypertable right away.</p><h3 id="data-retention">Data retention</h3><p>The final thing we wanted to accomplish with our continuous aggregates was a way to <em>keep</em> aggregated data around after dropping the raw data. This is impossible with both PostgreSQL views and materialized views because, for views, they work directly on the raw data—if you drop it, they can’t aggregate it. </p><p></p><p>With materialized views it’s a bit more complicated: until you run a refresh, they can have the old data around, but, once you run a refresh,  to get the new data that you’ve added in more recent time periods, then the old data is dropped. </p><p></p><p>With continuous aggregates, the implementation is much simpler. We mentioned the invalidation trigger that fires when we modify data that we’ve already materialized. We simply ignore any events older than a certain time horizon, including the drop event. </p><p></p><p>We also can process any invalidations before dropping data so that you can have the correct data materialized from right before you dropped the oldest stuff. You can configure data retention <a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/data-retention/data-retention-with-continuous-aggregates/">by setting up your continuous aggregate policy correctly</a>.</p><h2 id="does-it-work">Does It Work?</h2><p>So we’ve got this whole mashup of views and materialized views and triggers in order to try to make a good set of trade-offs that works well for time-series data. So the question is: does it work? </p><p><br><br>To test that, I recreated our continuous aggregate from above without data and a policy and ran the <code>refresh_continuous_aggregate</code> procedure so that it would have approximately a month’s worth of data in materialized in the aggregate, with about 30 minutes that need to go through the real-time view.</p><p><br><br>If we <strong>query for the aggregated data over the whole period from the continuous aggregate</strong>, it takes about<strong> 18 ms</strong>, which is slightly slower than the <strong>5-6 ms for the fully materialized data in a materialized view</strong>, but it’s still <strong>1,000x faster than the 15 s it takes from a normal view</strong>, <strong>and we get <em>most</em> of the up-to-date benefits of a normal view from it. </strong>I'd be pretty happy with that trade-off.</p><p></p><p>If you are new to TimescaleDB and would like to try this out, I invite you to <a href="https://console.cloud.timescale.com/signup">sign up for Timescale</a>. It's the easiest way to get started with Timescale. It’s 100 percent free for 30 days, no credit card required, and you’ll be able to spin up a database in seconds. </p><p>You can easily host PostgreSQL tables and TimescaleDB hypertables in your Timescale demo database, create views, materialized views, and continuous aggregates, and explore the differences in performance and developer experience between them. We've put together some extra directions in this guide on <a href="https://www.timescale.com/learn/postgresql-materialized-views-and-where-to-find-them">using incremental materialized views, a.k.a. continuous aggregates</a>—we hope it helps!<br><br></p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Pipelines: Building Functional Programming Into PostgreSQL Using Custom Operators]]></title>
            <description><![CDATA[Function pipelines allow you to analyze data by composing multiple functions in SQL and express complex logic in PostgreSQL in a cleaner way.]]></description>
            <link>https://www.tigerdata.com/blog/function-pipelines-building-functional-programming-into-postgresql-using-custom-operators</link>
            <guid isPermaLink="true">https://www.tigerdata.com/blog/function-pipelines-building-functional-programming-into-postgresql-using-custom-operators</guid>
            <category><![CDATA[Announcements & Releases]]></category>
            <category><![CDATA[PostgreSQL]]></category>
            <category><![CDATA[Engineering]]></category>
            <dc:creator><![CDATA[David Kohn]]></dc:creator>
            <pubDate>Tue, 19 Oct 2021 13:33:44 GMT</pubDate>
            <media:content medium="image" href="https://timescale.ghost.io/blog/content/images/2024/06/Function-pipelines--1-.png">
            </media:content>
            <content:encoded><![CDATA[<p><strong>Today, we are announcing <em>function pipelines</em>, a new capability that introduces functional programming concepts inside PostgreSQL (and SQL) using custom operators.</strong></p><p><em>Function pipelines</em> radically improve the developer ergonomics of analyzing data in PostgreSQL and SQL, by applying principles from <a href="https://en.wikipedia.org/wiki/Functional_programming">functional programming</a> and popular tools like <a href="https://pandas.pydata.org/docs/index.html">Python’s Pandas</a> and <a href="https://prometheus.io/docs/prometheus/latest/querying/basics/">PromQL</a>.</p><p>At Timescale, our mission is to serve developers worldwide and enable them to build exceptional data-driven products that measure everything that matters: software applications, industrial equipment, financial markets, blockchain activity, user actions, consumer behavior, machine learning models, climate change, and more.</p><p><a href="https://timescale.ghost.io/blog/blog/why-sql-beating-nosql-what-this-means-for-future-of-data-time-series-database-348b777b847a/">We believe SQL is the best language for data analysis</a>. We’ve championed its benefits for several years, even when many were abandoning it for custom domain-specific languages. And we were right—SQL has resurged and become the universal language for data analysis, and now many NoSQL databases are adding SQL interfaces to keep up.</p><p>But SQL is not perfect and, at times, can get quite unwieldy. For example,</p><pre><code class="language-SQL">SELECT device_id, 
	sum(abs_delta) as volatility
FROM (
	SELECT device_id, 
		abs(val - lag(val) OVER (PARTITION BY device_id ORDER BY ts))
        	as abs_delta 
	FROM measurements
	WHERE ts &gt;= now() - '1 day'::interval) calc_delta
GROUP BY device_id; </code></pre><p><em>Pop quiz: What does this query do?</em> </p><p>Even if you are a SQL expert, queries like this can be quite difficult to read—and even harder to express. Complex data analysis in SQL can be hard.</p><h2 id="the-advantages-of-function-pipelines">The Advantages of Function Pipelines</h2><p><em>Function pipelines</em> let you express that same query like this:</p><pre><code class="language-SQL">SELECT device_id, 
	timevector(ts, val) -&gt; sort() -&gt; delta() -&gt; abs() -&gt; sum() 
    		as volatility
FROM measurements
WHERE ts &gt;= now() - '1 day'::interval
GROUP BY device_id;</code></pre><p>Now it is much clearer what this query is doing:</p><ul><li>It gets the last day’s data from the measurements table, grouped by <code>device_id</code>.</li><li>It sorts the data by the time column.</li><li>It calculates the delta (or change) between values.</li><li>It takes the absolute value of the delta.</li><li>And then takes the sum of the results of the previous steps.</li></ul><p><strong>Function pipelines improve your own coding productivity, while also making your SQL code easier for others to comprehend and maintain.</strong></p><p>Inspired by functional programming languages, function pipelines enable you to analyze data by composing multiple functions, leading to a simpler, cleaner way of expressing complex logic in PostgreSQL.</p><p>The best part is that we built function pipelines in a way that is fully PostgreSQL compliant—we did not change any SQL syntax—meaning that any tool that speaks PostgreSQL will be able to support data analysis using function pipelines.</p><h2 id="how-we-built-function-pipelines">How We Built Function Pipelines</h2><p>How did we build this? By taking advantage of PostgreSQL's incredible extensibility, particularly custom types, operators, and <a href="https://www.postgresql.org/docs/current/sql-createtype.html">custom types</a>, <a href="https://www.postgresql.org/docs/current/sql-createoperator.html">custom operators</a>, and <a href="https://www.postgresql.org/docs/current/sql-createfunction.html">functions</a>.</p><p>In our previous example, you can see the key elements of function pipelines:</p><ul><li><strong>Custom data types</strong>: in this case, the <code>timevector</code>, which is a set of <code>(time, value)</code> pairs.</li><li><strong>Custom operator</strong>: <code>-&gt;</code>, used to <em>compose</em> and <em>apply </em>function pipeline elements to the data that comes in.</li><li>And finally, <strong>custom functions,</strong> called <em>pipeline elements. </em>Pipeline elements can transform and analyze <code>timevector</code>s (or other data types) in a function pipeline. For this initial release, we’ve built <em>60 custom functions! </em><strong>(</strong><a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/function-pipelines/"><strong>Full list here</strong></a><strong>)</strong>.</li></ul><p>We’ll go into more detail on function pipelines in the rest of this post, but if you just want to get started as soon as possible, <strong>the easiest way to try function pipelines is through a fully managed Timescale Cloud service</strong>. <a href="https://console.cloud.timescale.com/signup">Try it for free</a> (no credit card required) for 30 days. </p><p>Function pipelines are pre-loaded on each new database service on Timescale Cloud, available immediately—so after you’ve created a new service, you’re all set to use them!</p><p>If you prefer to manage your own database instances, <a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/install-toolkit/">you can install the <code>timescaledb_toolkit</code></a> into your existing PostgreSQL installation, completely for free. </p><p>We’ve been working on this capability for a long time, but in line with our belief of “<a href="https://timescale.ghost.io/blog/blog/move-fast-but-dont-break-things-introducing-the-experimental-schema-with-new-experimental-features-in-timescaledb-2-4/">move fast but don’t break things</a>,” we’re initially releasing function pipelines as an <a href="https://docs.timescale.com/api/latest/api-tag-overview/#experimental-timescaledb-toolkit">experimental feature</a>—and we would absolutely love to <strong>get your feedback</strong>. You can <a href="https://github.com/timescale/timescaledb-toolkit/issues">open an issue</a> or join a <a href="https://github.com/timescale/timescaledb-toolkit/discussions">discussion thread</a> in GitHub (and, if you like what you see, GitHub ⭐ is always welcome and appreciated, too!).</p><p><em>We’d also like to take this opportunity to give a huge shoutout to </em><a href="https://github.com/zombodb/pgx"><em><code>pgx</code>, the Rust-based framework for building PostgreSQL extensions</em></a><em>—it handles a lot of the heavy lifting for this project. We have over 600 custom types, operators, and functions in the <code>timescaledb_toolkit</code> extension at this point; managing this without <code>pgx</code> (and the ease of use that comes from working with Rust) would be a real bear of a job.</em></p><h2 id="function-pipelines-why-are-they-useful">Function Pipelines: Why Are They Useful?</h2><p>It’s October. In the northern hemisphere (where most of Team Timescale, including your author, lives), it is starting to get cold.</p><p>Now imagine a restaurant in New York City whose owners care about their customers and their customers’ comfort. And you are working on an IoT product designed to help small businesses like these owners minimize their heating bill while maximizing their customers happiness. So you install two thermometers, one at the front measuring the temperature right by the door, and another at the back of the restaurant.</p><p>Now, as many of you may know (if you’ve ever had to sit by the door of a restaurant in the fall or winter), when someone enters, the temperature drops—and once the door is closed, the temperature warms back up. The temperature at the back of the restaurant will vary much less than at the front, right by the door. Both of them will drop slowly down to a lower set point during non-business hours and warm back up sometime before business hours based on the setpoints on our thermostat. So overall we’ll end up with a graph that looks something like this:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/10/graph--1-.jpg" class="kg-image" alt="A graph with time on the x axis and temperature on the y axis showing two curves. First a curve labeled back which starts low steadily rises stays relatively constant in the section labeled operating hours and then drops slowly back down. Second a curve labeled front which starts following the other, starts low, rises then it starts getting jumpy, drastically varying while the other stays constant during operating hours, then it falls back down. " loading="lazy" width="1600" height="986" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/10/graph--1-.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/10/graph--1-.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/10/graph--1-.jpg 1600w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A graph of the temperature at the front (near the door) and back. The back is much steadier, while the front is more volatile. Graph is for illustrative purposes only, data is fabricated. No restaurants or restaurant patrons were harmed in the making of this post.</span></figcaption></figure><p>As we can see, the temperature by the front door varies much more than at the back of the restaurant. Another way to say this is the temperature by the front door is more <em>volatile</em>. Now, the owners of this restaurant want to measure this because frequent temperature changes means uncomfortable customers.</p><p>In order to measure volatility, we could first subtract each point from the point before to calculate a delta. If we add this up directly, large positive and negative deltas will cancel out. But, we only care about the magnitude of the delta, not its sign—so what we really should do is take the absolute value of the delta, and then take the total sum of the previous steps.</p><p>We now have a metric that might help us measure customer comfort, and also the efficacy of different weatherproofing methods (for example, adding one of those little vestibules that acts as a windbreak). </p><p>To track this, we collect measurements from our thermometers and store them in a table:</p><pre><code class="language-SQL">CREATE TABLE measurements(
	device_id BIGINT,
	ts TIMESTAMPTZ,
	val DOUBLE PRECISION
);
</code></pre><p>The <code>device_id</code> identifies the thermostat, <code>ts</code> the time of reading and <code>val</code> the temperature. </p><p>Using the data in our measurements table, let’s look at how we calculate volatility using function pipelines.</p><p><em>Note: because all of the function pipeline features are still experimental, they exist in the <code>toolkit_experimental</code> schema. Before running any of the SQL code in this post you will need to set your <code>search_path</code> to include the experimental schema as we do in the example below, we won’t repeat this throughout the post so as not to distract.</em></p><pre><code class="language-SQL">set search_path to toolkit_experimental, public; --still experimental, so do this to make it easier to read

SELECT device_id, 
	timevector(ts, val) -&gt; sort() -&gt; delta() -&gt; abs() -&gt; sum() 
    	as volatility
FROM measurements
WHERE ts &gt;= now()-'1 day'::interval
GROUP BY device_id;</code></pre><p>And now we have the same query that we used as our example in the introduction.</p><p>In this query, the function pipeline <code>timevector(ts, val) -&gt; sort() -&gt; delta() -&gt; abs() -&gt; sum()</code> succinctly expresses the following operations:</p><ol><li>Create <code>timevector</code>s (more detail on this later) out of the <code>ts</code> and <code>val</code> columns.</li><li>Sort each <code>timevector</code> by the time column.</li><li>Calculate the delta (or change) between each pair in the <code>timevector</code> by subtracting the previous <code>val</code> from the current.</li><li>Take the absolute value of the delta.</li><li>Take the sum of the results from the previous steps.</li></ol><p>The <code>FROM</code>, <code>WHERE</code> and <code>GROUP BY</code> clauses do the rest of the work telling us:</p><ol><li>We’re getting data <em>FROM</em> the <code>measurements</code> table</li><li><em>WHERE </em>the ts, or timestamp column, contains values over the last day</li><li>Showing one pipeline output per <code>device_id</code> (the GROUP BY column)</li></ol><p>As we noted before, if you were to do this same calculation using SQL and PostgreSQL functionality, your query would look like this:</p><pre><code class="language-SQL">SELECT device_id, 
sum(abs_delta) as volatility
FROM (
	SELECT 
		abs(val - lag(val) OVER (PARTITION BY device_id ORDER BY ts) ) 
        	as abs_delta 
	FROM measurements
	WHERE ts &gt;= now() - '1 day'::interval) calc_delta
GROUP BY device_id; 
</code></pre><p>This does the same five steps as the above but is much harder to understand. We have to use a <a href="https://www.postgresql.org/docs/current/functions-window.html">window function</a> and aggregate the results—but also, because aggregates are performed before window functions, we need to actually execute the window function in a subquery.</p><p>As we can see, function pipelines make it significantly easier to comprehend the overall analysis of our data. There’s no need to completely understand what’s going on in these functions just yet, but for now, it’s enough to understand that we’ve essentially implemented a small functional programming language inside of PostgreSQL. You can still use all of the normal, expressive SQL you’ve come to know and love. Function pipelines just add new tools to your SQL toolbox that make it easier to work with time-series data.</p><p>Some avid SQL users might find the syntax a bit foreign at first, but for many people who work in other programming languages, especially using tools like <a href="https://pandas.pydata.org/docs/index.html">Python’s Pandas Package</a>, this type of <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.pipe.html">successive operation on data sets</a> will feel natural. </p><p>Again, this is still fully PostgreSQL-compliant: we introduce no changes to the parser or anything that should break compatibility with PostgreSQL drivers.</p><h2 id="building-function-pipelines-without-forking-postgresql">Building Function Pipelines Without Forking PostgreSQL</h2><p>We built function pipelines—without modifying the <a href="https://www.postgresql.org/docs/10/parser-stage.html">parser</a> or anything that would require a fork of PostgreSQL—by taking advantage of three of the many ways that PostgreSQL enables extensibility: <a href="https://www.postgresql.org/docs/current/sql-createtype.html">custom types</a>, <a href="https://www.postgresql.org/docs/current/sql-createfunction.html">custom functions</a>, and <a href="https://www.postgresql.org/docs/current/sql-createoperator.html">custom operators</a>.</p><ul><li><strong>Custom data types</strong>, starting with the <code>timevector</code>, which is a set of <code>(time, value)</code> pairs</li><li><strong>A custom operator</strong>: <code>-&gt;</code>, which is used to <em>compose</em> and <em>apply </em>function pipeline elements to the data that comes in.</li><li><strong>Custom functions</strong>, called <em>pipeline elements</em>, which can transform and analyze <code>timevector</code>s (or other data types) in a function pipeline (with 60 functions in this initial release)</li></ul><p>We believe that new idioms like these are exactly what PostgreSQL was <em>meant to enable</em>. That’s why it has supported custom types, functions and operators from its earliest days. (And is one of the many reasons why we love PostgreSQL.)</p><h2 id="a-custom-data-type-the-timevector">A Custom Data Type: The <code>timevector</code></h2><p>A <code>timevector</code> is a collection of <code>(time, value)</code> pairs. As of now, the times must be <code>TIMESTAMPTZ</code>s and the values must be <code>DOUBLE PRECISION</code> numbers. (But this may change in the future as we continue to develop this data type. If you have ideas/input, please <a href="https://github.com/timescale/timescaledb-toolkit/issues">file feature requests on GitHub</a> explaining what you’d like!)</p><p>You can think of the <code>timevector</code> as something like this: </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/10/table1--1-.jpg" class="kg-image" alt=" A box with `timevector` on the outside, inside there is a table with one column labeled time containing multiple timestamps and another column labeled value containing floating point numbers." loading="lazy" width="950" height="880" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/10/table1--1-.jpg 600w, https://timescale.ghost.io/blog/content/images/2021/10/table1--1-.jpg 950w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A depiction of a </span><code spellcheck="false" style="white-space: pre-wrap;"><span>timevector</span></code><span style="white-space: pre-wrap;">.</span></figcaption></figure><p>One of the first questions you might ask is: how does a <code>timevector</code> relate to time-series data? (If you want to know more about time-series data, <a href="https://timescale.ghost.io/blog/time-series-data/" rel="noreferrer">we have a great blog post on that</a>,). </p><p>Let’s consider our example from above, where we were talking about a restaurant that was measuring temperatures, and we had a <code>measurements</code> table like so:</p><pre><code class="language-SQL">CREATE TABLE measurements(
	device_id BIGINT,
	ts TIMESTAMPTZ,
	val DOUBLE PRECISION
);
</code></pre><p>In this example, we can think of a single time-series dataset as all historical and future time and temperature measurements from a device. </p><p>Given this definition, we can think of a <code>timevector</code> as a <strong>finite subset of a time-series dataset</strong>. The larger time-series dataset may extend back into the past, and it may extend into the future, but the <code>timevector</code> is bounded.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/10/table2--1-.jpg" class="kg-image" alt="A box labeled time-series with a table in it. The table has one column labeled time and another labeled value like the diagram above. There is a timevector box inside the table with timestamps and values. Each column also has an arrow at the top pointing to the word past and another arrow at the bottom pointing to the word future conveying that the time-series extends into the past and future while the timevector contains a subset of the values. " loading="lazy" width="1200" height="1500" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/10/table2--1-.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/10/table2--1-.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/10/table2--1-.jpg 1200w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A </span><code spellcheck="false" style="white-space: pre-wrap;"><span>timevector</span></code><span style="white-space: pre-wrap;"> is a finite subset of a time-series and contains all the </span><code spellcheck="false" style="white-space: pre-wrap;"><span>(time, value)</span></code><span style="white-space: pre-wrap;"> pairs in some region of the time-series.</span></figcaption></figure><p>In order to construct a <code>timevector</code> from the data gathered from a thermometer, we use a custom aggregate and pass in the columns we want to become our <code>(time, value)</code> pairs. We can use the <code>WHERE</code> clause to define the extent of the <code>timevector</code> (i.e., the limits of this subset), and the <code>GROUP BY</code> clause to provide identifying information about the <a href="https://www.tigerdata.com/blog/time-series-introduction" rel="noreferrer">time series</a> that are represented.</p><p>Building on our example, this is how we construct a <code>timevector</code> for each thermometer in our dataset:</p><pre><code class="language-SQL">SELECT device_id, 
	timevector(ts, val)
FROM measurements
WHERE ts &gt;= now() - '1 day'::interval
GROUP BY device_id;
</code></pre><p>But a <code>timevector</code> doesn't provide much value by itself. So now, let’s also consider some complex calculations that we can apply to the <code>timevector</code>, starting with a custom operator used to apply these functions</p><h2 id="a-custom-operator">A Custom Operator: <code>-&gt;</code></h2><p><br>In function pipelines, the <code>-&gt;</code> operator is used to apply and compose multiple functions, in an easy to write and read format. </p><p>Fundamentally, <code>-&gt;</code> means: “apply the operation on the right to the inputs on the left”, or, more simply “do the next thing”. </p><p>We created a general-purpose operator for this because we think that too many operators meaning different things can get very confusing and difficult to read.</p><p>One thing that you’ll notice about the pipeline elements is that the arguments are in an unusual place in a statement like:</p><pre><code class="language-SQL">SELECT device_id, 
 	timevector(ts, val) -&gt; sort() -&gt; delta() -&gt; abs() -&gt; sum() 
    	as volatility
FROM measurements
WHERE ts &gt;= now() - '1 day'::interval
GROUP BY device_id;</code></pre><p>It <em>appears </em>(from the semantics) that the <code>timevector(ts, val)</code> is an argument to <code>sort()</code>, the resulting <code>timevector</code> is an argument to <code>delta()</code> and so on. <br></p><p>The thing is that <code>sort()</code> (and the others) are regular function calls; they can’t see anything outside of their parentheses and don’t know about anything to their left in the statement; so we need a way to get the <code>timevector</code> into the <code>sort()</code> (and the rest of the pipeline). </p><p>We solved this by taking advantage of one of the fundamental computing insights that functional programming languages use: <em>code and data are really the same thing</em>. </p><p>Each of our functions returns a special type that describes the function and its arguments. We call these types <em>pipeline elements </em>(more later)<em>.</em> </p><p>The <code>-&gt;</code> operator then performs one of two different types of actions depending on the types on its right and left sides.  It can either:</p><ol><li><em>Apply</em> a pipeline element to the left-hand argument—perform the function described by the pipeline element directly on the incoming data type.</li><li><em>Compose pipeline elements into a combined element that can be applied at some point in the future (this is an optimization that allows us to apply multiple elements in a “nested” manner so that we don’t perform multiple unnecessary passes).</em></li></ol><p>The operator determines the action to perform based on its left and right arguments. </p><p>Let’s look at our <code>timevector</code> from before: <code>timevector(ts, val) -&gt; sort() -&gt; delta() -&gt; abs() -&gt; sum()</code>. If you remember from before, I noted that this function pipeline performs the following steps: </p><ol><li>Create <code>timevector</code>s out of the <code>ts</code> and <code>val</code> columns.</li><li>Sort it by the time column.</li><li>Calculate the delta (or change) between each pair in the <code>timevector</code> by subtracting the previous <code>val</code> from the current.</li><li>Take the absolute value of the delta.</li><li>Take the sum of the results from the previous steps.</li></ol><p>And logically, at each step, we can think of the <code>timevector</code> being materialized and passed to the next step in the pipeline. </p><p>However, while this will produce a correct result, it’s not the most efficient way to compute this. Instead, it would be more efficient to compute as much as possible in a single pass over the data.</p><p>In order to do this, we allow not only the <em>apply</em> operation, but also the <em>compose</em> operation. Once we’ve composed a pipeline into a logically equivalent higher order pipeline with all of the elements we can choose the most efficient way to execute it internally. (Importantly, even if we have to perform each step sequentially, we don’t need to <em>materialize</em> it and pass it between each step in the pipeline so it has significantly less overhead even without other optimization).</p><h2 id="custom-functions-pipeline-elements">Custom Functions: Pipeline Elements</h2><p>Now let’s discuss the third, and final, key piece that makes up function pipelines: custom functions, or as we call them, <em>pipeline elements</em>.</p><p>We have implemented over 60 individual pipeline elements, which fall into 4 categories (with a few subcategories):</p><h3 id="timevector-transforms"><code>timevector</code> transforms</h3><p>These elements take in a <code>timevector</code> and produce a <code>timevector</code>. They are the easiest to compose, as they produce the same type.</p><p>Example pipeline:</p><pre><code class="language-SQL">SELECT device_id, 
	timevector(ts, val) 
    	-&gt; sort() 
        -&gt; delta() 
        -&gt; map($$ ($value^3 + $value^2 + $value * 2) $$) 
        -&gt; lttb(100) 
FROM measurements</code></pre><p>Organized by sub-category:</p><h4 id="unary-mathematical">Unary mathematical</h4>
<p>Simple mathematical functions applied to the value in each point in a <code>timevector</code>. (<a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/function-pipelines/#unary-mathematical-functions">Docs link</a>)</p>
<table>
<thead>
<tr>
<th>Element</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>abs()</code></td>
<td>Computes the absolute value of each value</td>
</tr>
<tr>
<td><code>cbrt()</code></td>
<td>Computes the cube root of each value</td>
</tr>
<tr>
<td><code>ceil()</code></td>
<td>Computes the first integer greater than or equal to each value</td>
</tr>
<tr>
<td><code>floor()</code></td>
<td>Computes the first integer less than or equal to each value</td>
</tr>
<tr>
<td><code>ln()</code></td>
<td>Computes the natural logarithm of each value</td>
</tr>
<tr>
<td><code>log10()</code></td>
<td>Computes the base 10 logarithm of each value</td>
</tr>
<tr>
<td><code>round()</code></td>
<td>Computes the closest integer to each value</td>
</tr>
<tr>
<td><code>sign()</code></td>
<td>Computes +/-1 for each positive/negative value</td>
</tr>
<tr>
<td><code>sqrt()</code></td>
<td>Computes the square root for each value</td>
</tr>
<tr>
<td><code>trunc()</code></td>
<td>Computes only the integer portion of each value</td>
</tr>
</tbody>
</table>
<h4 id="binary-mathematical">Binary mathematical</h4>
<p>Simple mathematical functions with a scalar input applied to the value in each point in a <code>timevector</code>. (<a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/function-pipelines/#binary-mathematical-functions">Docs link</a>)</p>
<table>
<thead>
<tr>
<th>Element</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>add(N)</code></td>
<td>Computes each value plus <code>N</code></td>
</tr>
<tr>
<td><code>div(N)</code></td>
<td>Computes each value divided by <code>N</code></td>
</tr>
<tr>
<td><code>logn(N)</code></td>
<td>Computes the logarithm base <code>N</code> of each value</td>
</tr>
<tr>
<td><code>mod(N)</code></td>
<td>Computes the remainder when each number is divided by <code>N</code></td>
</tr>
<tr>
<td><code>mul(N)</code></td>
<td>Computes each value multiplied by <code>N</code></td>
</tr>
<tr>
<td><code>power(N)</code></td>
<td>Computes each value taken to the <code>N</code> power</td>
</tr>
<tr>
<td><code>sub(N)</code></td>
<td>Computes each value less <code>N</code></td>
</tr>
</tbody>
</table>
<h4 id="compound-transforms">Compound transforms</h4>
<p>Transforms involving multiple points inside of a <code>timevector</code>. (<a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/function-pipelines/#compound-transforms">Docs link</a>)</p>
<table>
<thead>
<tr>
<th>Element</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>delta()</code></td>
<td>Subtracts each value from the previous`</td>
</tr>
<tr>
<td><code>fill_to(interval, fill_method)</code></td>
<td>Fills gaps larger than <code>interval</code> with points at <code>interval</code> from the previous using <code>fill_method</code></td>
</tr>
<tr>
<td><code>lttb(resolution)</code></td>
<td>Downsamples a <code>timevector</code> using the largest triangle three buckets algorithm at `resolution, requires sorted input.</td>
</tr>
<tr>
<td><code>sort()</code></td>
<td>Sorts the <code>timevector</code> by the <code>time</code> column ascending</td>
</tr>
</tbody>
</table>
<h4 id="lambda-elements">Lambda elements</h4>
<p>These elements use lambda expressions, which allows the user to write small functions to be evaluated over each point in a <code>timevector</code>.<br>
Lambda expressions can return a <code>DOUBLE PRECISION</code> value like <code>$$ $value^2 + $value + 3 $$</code>. They can return a <code>BOOL</code> like <code>$$ $time &gt; ‘2020-01-01’t $$</code> .  They can also return a <code>(time, value)</code> pair like <code>$$ ($time + ‘1 day’i, sin($value) * 4)$$</code>. (<a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/function-pipelines/#lambda-elements">Docs link</a>)</p>
<p>You can apply them using the elements below:</p>
<table>
<thead>
<tr>
<th>Element</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>filter(lambda (bool) )</code></td>
<td>Removes points from the <code>timevector</code> where the lambda expression evaluates to <code>false</code></td>
</tr>
<tr>
<td><code>map(lambda (value) )</code></td>
<td>Applies the lambda expression to all the values in the <code>timevector</code></td>
</tr>
<tr>
<td><code>map(lambda (time, value) )</code></td>
<td>Applies the lambda expression to all the times and values in the <code>timevector</code></td>
</tr>
</tbody>
</table>
<h3 id="timevector-finalizers"><code>timevector</code> finalizers</h3><p>These elements end the <code>timevector</code> portion of a pipeline, they can either help with output or  produce an aggregate over the entire <code>timevector</code>. They are an optimization barrier to composition as they (usually) produce types other than <code>timevector</code>.</p><p>Example pipelines:</p><pre><code class="language-SQL">SELECT device_id, 
	timevector(ts, val) -&gt; sort() -&gt; delta() -&gt; unnest()
FROM measurements</code></pre><pre><code class="language-SQL">SELECT device_id, 
	timevector(ts, val) -&gt; sort() -&gt; delta() -&gt; time_weight()
FROM measurements</code></pre><p>Finalizer pipeline elements organized by sub-category:</p><h4 id="timevector-output"><code>timevector</code> output</h4>
<p>These elements help with output, and can produce a set of <code>(time, value)</code> pairs or a Note: this is an area where we’d love further feedback, are there particular data formats that would be especially useful for, say graphing that we can add? <a href="https://github.com/timescale/timescaledb-toolkit/issues">File an issue in our GitHub</a>!</p>
<table>
<thead>
<tr>
<th>Element</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>unnest( )</code></td>
<td>Produces a set of <code>(time, value)</code> pairs. You can wrap and expand as a composite type to produce separate columns <code>(pipe -&gt; unnest()).*</code></td>
</tr>
<tr>
<td><code>materialize()</code></td>
<td>Materializes a <code>timevector</code> to pass to an application or other operation directly, blocks any optimizations that would materialize it lazily.</td>
</tr>
</tbody>
</table>
<h4 id="timevector-aggregates"><code>timevector</code> aggregates</h4>
<p>Aggregate all the points in a <code>timevector</code> to produce a single value as a result. (<a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/function-pipelines/#aggregate-output-elements">Docs link</a>)</p>
<table>
<thead>
<tr>
<th>Element</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>average()</code></td>
<td>Computes the average of the values in the <code>timevector</code></td>
</tr>
<tr>
<td><code>counter_agg()</code></td>
<td>Computes the <code>counter_agg</code> aggregate over the times and values in the <code>timevector</code></td>
</tr>
<tr>
<td><code>stats_agg()</code></td>
<td>Computes a range of statistical aggregates and returns a <code>1DStatsAgg</code> over the values in the <code>timevector</code></td>
</tr>
<tr>
<td><code>sum()</code></td>
<td>Computes the sum of the values in the <code>timevector</code></td>
</tr>
<tr>
<td><code>num_vals()</code></td>
<td>Counts the points in the <code>timevector</code></td>
</tr>
</tbody>
</table>
<h2 id="aggregate-accessors-and-mutators">Aggregate Accessors and Mutators</h2><p>These function pipeline elements act like the accessors that I described in our previous <a href="https://timescale.ghost.io/blog/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design-2/">post on aggregates</a>. You can use them to get a value from the aggregate part of a function pipeline like so:</p><pre><code class="language-SQL">SELECT device_id, 
	timevector(ts, val) -&gt; sort() -&gt; delta() -&gt; stats_agg() -&gt; variance() 
FROM measurements
</code></pre><p>But these don’t <em>just</em> work on <code>timevector</code>s - they also work on a normally produced aggregate as well. </p><p>When used instead of normal function accessors and mutators they can make the syntax more clear by getting rid of nested functions like:</p><pre><code class="language-SQL">SELECT approx_percentile(0.5, percentile_agg(val)) 
FROM measurements
</code></pre><p>Instead, we can use the arrow accessor to convey the same thing: </p><pre><code class="language-SQL">SELECT percentile_agg(val) -&gt; approx_percentile(0.5) 
FROM measurements
</code></pre><p>By aggregate family:</p><h4 id="counter-aggregates">Counter aggregates</h4>
<p><a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/counter-aggregation/counter-aggs/#counter-aggregates">Counter aggregates</a> deal with resetting counters, (and were stabilized in our 1.3 release this week!). Counters are a common type of metric in the application performance monitoring and metrics world. All values have resets accounted for. These elements must have a <code>CounterSummary</code> to their left when used in a pipeline, from a <code>counter_agg()</code> aggregate or pipeline element. (<a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/function-pipelines/#counter-aggregates">Docs link</a>)</p>
<table>
<thead>
<tr>
<th>Element</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>counter_zero_time()</code></td>
<td>The time at which the counter value is predicted to have been zero based on the least squares fit of the points input to the <code>CounterSummary</code>(x intercept)</td>
</tr>
<tr>
<td><code>corr()</code></td>
<td>The correlation coefficient of the least squares fit line of the adjusted counter value.</td>
</tr>
<tr>
<td><code>delta()</code></td>
<td>Computes the last - first value of the counter</td>
</tr>
<tr>
<td><code>extapolated_delta(method)</code></td>
<td>Computes the delta extrapolated using the provided method to bounds of range. Bounds must have been provided in the aggregate or a <code>with_bounds</code> call</td>
</tr>
<tr>
<td><code>idelta_left()</code> / <code>idelta_right()</code></td>
<td>Computes the instantaneous difference between the second and first points (left) or last and next-to-last points (right)</td>
</tr>
<tr>
<td><code>intercept()</code></td>
<td>The y-intercept of the least squares fit line of the adjusted counter value.</td>
</tr>
<tr>
<td><code>irate_left()</code> / <code>irate_right()</code></td>
<td>Computes the instantaneous rate of change between the second and first points (left) or last and next-to-last points (right)</td>
</tr>
<tr>
<td><code>num_changes()</code></td>
<td>Number of times the counter changed values.</td>
</tr>
<tr>
<td><code>num_elements()</code></td>
<td>Number of items - any with the exact same time will have been counted only once.</td>
</tr>
<tr>
<td><code>num_changes()</code></td>
<td>Number of times the counter reset.</td>
</tr>
<tr>
<td><code>slope()</code></td>
<td>The slope of the least squares fit line of the adjusted counter value.</td>
</tr>
<tr>
<td><code>with_bounds(range)</code></td>
<td>Applies bounds using the <code>range</code> (a <code>TSTZRANGE</code>) to the <code>CounterSummary</code> if they weren’t provided in the aggregation step</td>
</tr>
</tbody>
</table>
<h4 id="percentile-approximation">Percentile approximation</h4>
<p>These aggregate accessors deal with <a href="https://timescale.ghost.io/blog/blog/how-percentile-approximation-works-and-why-its-more-useful-than-averages/">percentile approximation</a>. For now we’ve only implemented them for <code>percentile_agg</code> and <code>uddsketch</code> based aggregates. We have not yet implemented them for <code>tdigest</code>. (<a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/function-pipelines/#percentile-approximation">Docs link</a>)</p>
<table>
<thead>
<tr>
<th>Element</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>approx_percentile(p)</code></td>
<td>The approximate value at percentile <code>p</code></td>
</tr>
<tr>
<td><code>approx_percentile_rank(v)</code></td>
<td>The approximate percentile a value <code>v</code> would fall in</td>
</tr>
<tr>
<td><code>error()</code></td>
<td>The maximum relative error guaranteed by the approximation</td>
</tr>
<tr>
<td><code>mean()</code></td>
<td>The exact average of the input values.</td>
</tr>
<tr>
<td><code>num_vals()</code></td>
<td>The number of input values</td>
</tr>
</tbody>
</table>
<h4 id="statistical-aggregates">Statistical aggregates</h4>
<p>These aggregate accessors add support for common statistical aggregates  (and were stabilized in our 1.3 release this week!). These allow you to compute and <code>rollup()</code> common statistical aggregates like <code>average</code>, <code>stddev</code> and more advanced ones like <code>skewness</code> as well as 2-dimensional aggregates like <code>slope</code> and <code>covariance</code>.  Because there are both 1D and 2D versions of these, the accessors can have multiple forms, for instance, <code>average()</code> calculates the average on a 1D aggregate while <code>average_y()</code> &amp; <code>average_x()</code> do so on each dimension of a 2D aggregate. (<a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/function-pipelines/#statistical-aggregates">Docs link</a>)</p>
<table>
<thead>
<tr>
<th>Element</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>average() / average_y() / average_x()</code></td>
<td>The average of the values.</td>
</tr>
<tr>
<td><code>corr()</code></td>
<td>The correlation coefficient of the least squares fit line.</td>
</tr>
<tr>
<td><code>covariance(method)</code></td>
<td>The covariance of the values using either <code>population</code> or <code>sample</code> method.</td>
</tr>
<tr>
<td><code>determination_coeff()</code></td>
<td>The determination coefficient (aka R squared)  of the values.</td>
</tr>
<tr>
<td><code>kurtosis(method) / kurtosis_y(method) / kurtosis_x(method)</code></td>
<td>The kurtosis (4th moment) of the values using either <code>population</code> or <code>sample</code> method.</td>
</tr>
<tr>
<td><code>intercept()</code></td>
<td>The intercept of the least squares fit line.</td>
</tr>
<tr>
<td><code>num_vals()</code></td>
<td>The number of (non-null) values seen.</td>
</tr>
<tr>
<td><code>sum() / sum_x() / sum_y()</code></td>
<td>The sum of the values seen.</td>
</tr>
<tr>
<td><code>skewness(method) / skewness_y(method) / skewness_x(method)</code></td>
<td>The skewness (3rd moment) of the values using either <code>population</code> or <code>sample</code> method.</td>
</tr>
<tr>
<td><code>slope()</code></td>
<td>The slope of the least squares fit line.</td>
</tr>
<tr>
<td><code>stddev(method) / stddev_y(method) / stddev_x(method)</code></td>
<td>The standard deviation of the values using either <code>population</code> or <code>sample</code> method.</td>
</tr>
<tr>
<td><code>variance(method) / variance_y(method) / variance_x(method)</code></td>
<td>The variance of the values using either <code>population</code> or <code>sample</code> method.</td>
</tr>
<tr>
<td><code>x_intercept()</code></td>
<td>The x intercept of the least squares fit line.</td>
</tr>
</tbody>
</table>
<h4 id="time-weighted-averages">Time-weighted averages</h4>
<p>(<a href="https://timescale.ghost.io/blog/blog/what-time-weighted-averages-are-and-why-you-should-care/">More info</a>)<br>
The <code>average()</code> accessor may be called on the output of a <code>time_weight()</code> like so:</p>
<pre><code class="language-SQL">SELECT time_weight('Linear', ts, val) -&gt; average()  FROM measurements;
</code></pre><h4 id="approximate-count-distinct-hyperloglog">Approximate count distinct (Hyperloglog)</h4>
<p>This is an approximation for distinct counts that was stabilized in our 1.3 release!(<a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/hyperfunctions/approx-count-distincts/">Docs link</a>) The <code>distinct_count()</code> accessor may be called on the output of a <code>hyperloglog()</code> like so:</p>
<pre><code class="language-SQL">SELECT hyperloglog(device_id) -&gt; distinct_count() FROM measurements;
</code></pre><h2 id="next-steps">Next Steps</h2><p>We hope this post helped you understand how function pipelines leverage PostgreSQL extensibility to offer functional programming concepts in a way that is fully PostgreSQL compliant. And how function pipelines can improve the ergonomics of your code, making it easier to write, read, and maintain. </p><p><a href="https://console.cloud.timescale.com/signup"><strong>You can try function pipelines today</strong></a> with a fully managed Timescale Cloud service (no credit card required, free for 30 days). Function pipelines are available now on every new database service on Timescale Cloud, so after you’ve created a new service, you’re all set to use them!</p><p>If you prefer to manage your own database instances, you can <a href="https://github.com/timescale/timescaledb-toolkit">download and install the timescaledb_toolkit extension</a> on GitHub for free, after which you’ll be able to use function pipelines.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Percentiles Work (and Why They're Better Than Averages)]]></title>
            <description><![CDATA[Get a primer on percentile approximations and why they're useful for analyzing large time-series datasets.]]></description>
            <link>https://www.tigerdata.com/blog/how-percentiles-work-and-why-theyre-better-than-averages</link>
            <guid isPermaLink="true">https://www.tigerdata.com/blog/how-percentiles-work-and-why-theyre-better-than-averages</guid>
            <category><![CDATA[PostgreSQL]]></category>
            <category><![CDATA[Engineering]]></category>
            <category><![CDATA[Hyperfunctions]]></category>
            <dc:creator><![CDATA[David Kohn]]></dc:creator>
            <pubDate>Tue, 14 Sep 2021 15:41:30 GMT</pubDate>
            <media:content medium="image" href="https://timescale.ghost.io/blog/content/images/2021/09/maxim-hopman-fiXLQXAhCfk-unsplash--1-.jpg">
            </media:content>
            <content:encoded><![CDATA[<p>In my recent post on <a href="https://timescale.ghost.io/blog/blog/what-time-weighted-averages-are-and-why-you-should-care/">time-weighted averages</a>, I described how my early career as an electrochemist exposed me to the importance of time-weighted averages, which shaped how we built them into TimescaleDB hyperfunctions. </p><p>A few years ago, soon after I started learning more about PostgreSQL internals (check out my <a href="https://timescale.ghost.io/blog/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design-2/">aggregation and two-step aggregates</a> post to learn about them yourself!), I worked on backends for an ad analytics company, where I started using TimescaleDB.</p><p>Like most companies, we cared a lot about making sure our website and API calls returned results in a reasonable amount of time for the user; we had billions of rows in our analytics databases, but we still wanted to make sure that the website was responsive and useful. </p><p>There’s a direct correlation between website performance and business results: users get bored if they have to wait too long for results, which is obviously not ideal from a business and customer loyalty perspective. To understand how our website performed and find ways to improve, we tracked the timing of our API calls and used API call response time as a key metric.</p><p>Monitoring an API is a common scenario and generally falls under the category of application performance monitoring (APM), but there are lots of similar scenarios in other fields, including:</p><ol><li>Predictive maintenance for industrial machines</li><li>Fleet monitoring for shipping companies</li><li>Energy and water use monitoring and anomaly detection</li></ol><p>Of course, analyzing raw (usually time-series) data only gets you so far. You want to analyze trends, understand how your system performs relative to what you and your users expect, catch and fix issues before they impact production users, and so much more. We <a href="https://timescale.ghost.io/blog/blog/introducing-hyperfunctions-new-sql-functions-to-simplify-working-with-time-series-data-in-postgresql/">built TimescaleDB hyperfunctions to help solve this problem and simplify how developers work with time-series data</a>.</p><p>For reference, hyperfunctions are a series of SQL functions that make it easier to manipulate and analyze time-series data in PostgreSQL with fewer lines of code. You can use hyperfunctions to calculate percentile approximations of data, compute time-weighted averages, downsample and smooth data, and perform faster <code>COUNT DISTINCT</code> queries using approximations. </p><p>Moreover, hyperfunctions are “easy” to use: you call a hyperfunction using the same SQL syntax you know and love.</p><p>We spoke with community members to understand their needs, and our initial release includes some of the most frequently requested functions, including <strong>percentile approximations</strong> (see <a href="https://github.com/timescale/timescaledb-toolkit/issues/41">GitHub feature request and discussion</a>). </p><p>They’re very useful for working with large time-series data sets because they offer the benefits of using percentiles (rather than averages or other counting statistics) while still being quick and space-efficient to compute, parallelizable, and useful with continuous aggregates and other advanced TimescaleDB features.</p><p><strong>If you’d like to get started with the </strong><a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/"><strong>percentile approximation hyperfunctions</strong></a><strong>—and many more—right away, spin up a fully managed Timescale Cloud service: </strong>create an account to <a href="https://console.cloud.timescale.com/signup">try it for free</a> for 30 days. (Hyperfunctions are pre-loaded on each new database service on Timescale Cloud, so after you create a new service, you’re all set to use them).</p><p><strong>If you prefer to manage your own database instances, you can </strong><a href="https://github.com/timescale/timescaledb-toolkit"><strong>download and install the timescaledb_toolkit extension</strong></a> on GitHub, after which you’ll be able to use percentile approximation and other hyperfunctions.</p><p>Finally, we love building in public and continually improving:</p><ul><li>If you have questions or comments on this blog post, <a href="https://github.com/timescale/timescaledb-toolkit/discussions/185">we’ve started a discussion on our GitHub page, and we’d love to hear from you</a>. And, if you like what you see, GitHub ⭐ are always welcome and appreciated, too!</li><li>You can view our <a href="https://github.com/timescale/timescaledb-toolkit">upcoming roadmap on GitHub</a> for a list of proposed features, as well as features we’re currently implementing and those that are available to use today.</li></ul><h2 id="things-i-forgot-from-7th-grade-math-percentiles-vs-averages">Things I Forgot From 7th Grade Math: Percentiles vs. Averages</h2><p>I probably learned about averages, medians, and modes in 7th-grade math class, but if you’re anything like me, they may periodically get lost in the cloud of “things I learned once and thought I knew, but actually, I don’t remember quite as well as I thought.”</p><p>As I was researching this piece, I found a number of good blog posts (see examples from the folks at <a href="https://www.dynatrace.com/news/blog/why-averages-suck-and-percentiles-are-great/">Dynatrace</a>, <a href="https://www.elastic.co/blog/averages-can-dangerous-use-percentile">Elastic</a>, <a href="https://blog.appsignal.com/2018/12/04/dont-be-mean-statistical-means-and-percentiles-101.html">AppSignal</a>, and <a href="https://www.optimizely.com/insights/blog/why-cdn-balancing/">Optimizely</a>) about how averages aren’t great for understanding application performance, or other similar things and why it’s better to use percentiles.</p><p>I won’t spend too long on this, but I think it’s important to provide some background on <em>why</em> and <em>how</em> percentiles can help us better understand our data.</p><p>First off, let’s consider how percentiles and averages are defined. To understand this, let’s start by looking at a <a href="https://en.wikipedia.org/wiki/Normal_distribution"><strong>normal distribution</strong></a><strong>:</strong></p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-1.jpg" class="kg-image" alt="A graph with a Gaussian/normal distribution, it has a peak at the center, then falls off relatively sharply and symmetrically on either side. " loading="lazy" width="2000" height="1182" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2021/09/Graph-1.jpg 1600w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-1.jpg 2152w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A normal, or Gaussian, distribution describes many real-world processes that fall around a given value and where the probability of finding values that are further from the center decreases. The median, average, and mode are all the same for a normal distribution, and they fall on the dotted line at the center.</span></figcaption></figure><p>The normal distribution is what we often think of when we think about statistics; it’s one of the most frequently used and often used in introductory courses. In a normal distribution, the median, the average (also known as the mean), and the mode are all the same, even though they’re defined differently.</p><p>The <strong>median</strong> is the middle value, where half of the data is above and half is below. The <strong>mean</strong> (aka average) is defined as the sum(value) / count(value),  and the <strong>mode </strong>is defined as the most common or frequently occurring value.</p><p>When we’re looking at a curve like this, the x-axis represents the value, while the y-axis represents the frequency with which we see a given value (i.e., values that are “higher” on the y-axis occur more frequently).</p><p>In a normal distribution, we see a curve centered (the dotted line) at its most frequent value, with decreasing probability of seeing values further away from the most frequent one (the most frequent value is the mode). Note that the normal distribution is symmetric, which means that values to the left and right of the center have the same probability of occurring.</p><p>The median, or the middle value, is also known as the 50th percentile (the middle percentile out of 100). This is the value at which 50% of the data is less than the value, and 50% is greater than the value (or equal to it).</p><p>In the below graph, half of the data is to the left (shaded in blue), and half is to the right (shaded in yellow), with the 50th percentile directly in the center.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-2.jpg" class="kg-image" alt="A normal distribution as in the last graph, except now the left 50% of the graph is shaded in one color, the right in a different color. The dotted line in the center  is labeled median (50th percentile)" loading="lazy" width="2000" height="1182" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-2.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-2.jpg 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2021/09/Graph-2.jpg 1600w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-2.jpg 2152w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A normal distribution with the median/50th percentile depicted.</span></figcaption></figure><p>This leads us to percentiles: a <strong>percentile</strong> is defined as the value where x percent of the data falls below the value. </p><p>For example, if we call something “the 10th percentile,” we mean that 10% of the data is less than the value and 90% is greater than (or equal to) the value.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-3.jpg" class="kg-image" alt="The same as the last graph except the dotted line has shifted leftward, and now 10% of the area under the graph to the left of the line is shaded one color with 90% shaded a different color. The dotted line has been re-labeled as the 10th percentile." loading="lazy" width="2000" height="1182" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-3.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-3.jpg 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2021/09/Graph-3.jpg 1600w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-3.jpg 2152w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A normal distribution with the 10th percentile depicted.</span></figcaption></figure><p>And the 90th percentile is where 90% of the data is less than the value and 10% is greater:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-4.jpg" class="kg-image" alt="The same as the last graph except the line has shifted to the right and is now labeled 90th percentile, 90% of the area under the curve to the left of the line is shaded one color, the 10% to the right of the line is shaded a different color." loading="lazy" width="2000" height="1182" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-4.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-4.jpg 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2021/09/Graph-4.jpg 1600w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-4.jpg 2152w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A normal distribution with the 90th percentile depicted.</span></figcaption></figure><p>To calculate the 10th percentile, let’s say we have 10,000 values. We take all of the values, order them from smallest to largest, and identify the 1001st value (where 1000 or 10% of the values are below it), which will be our 10th percentile.</p><p>We noted before that the median and average are the same in a normal distribution. This is because a normal distribution is <em>symmetric</em>. Thus, the magnitude and number of points with values larger than the median are completely balanced (both in magnitude and number of points smaller than the median).</p><p>In other words, there is always the same number of points on either side of the median, but the <em>average</em> takes into account the actual value of the points. </p><p>For the median and average to be equal, the points less than the median and greater than the median must have the same distribution (i.e., there must be the same number of points that are somewhat larger and somewhat smaller and much larger and much smaller). (<strong>Correction:</strong> as pointed out to us in<a href="https://news.ycombinator.com/item?id=28527954"> a helpful comment on Hacker News</a>, technically, this is only true for symmetric distributions, asymmetric distributions it may or may not be true for, and you can get odd cases of asymmetric distributions where these are equal, though they are less likely!)</p><p><strong>Why is this important? </strong>The fact that the median and average are the same in the normal distribution can cause some confusion. Since a normal distribution is often one of the first things we learn, we (myself included!) can think it applies to more cases than it actually does.</p><p>It’s easy to forget or fail to realize that only the <em>median</em> guarantees that 50% of the values will be above and 50% below—while the average guarantees that 50% of the <strong>weighted</strong> values will be above and 50% below (i.e., the average is the <a href="https://en.wikipedia.org/wiki/Centroid">centroid</a>, while the median is the center).</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-5.jpg" class="kg-image" alt="The same graph as the one several graphs ago showing the median/50th percentile with half shaded one color and half another, except now the line is labeled as the average as well as the median. " loading="lazy" width="2000" height="1182" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-5.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-5.jpg 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2021/09/Graph-5.jpg 1600w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-5.jpg 2152w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">The average and median are the same in a normal distribution, and they split the graph exactly in half. But they aren’t calculated the same way, don’t represent the same thing, and aren’t necessarily the same in other distributions.</span></figcaption></figure><p>🙏 Shout out to the folks over at <a href="https://www.desmos.com/">Desmos</a> for their great graphing calculator, which helped make these graphs and even allowed me to make an <a href="https://www.desmos.com/calculator/ty3jt8ftgs">interactive demonstration of these concepts</a>!</p><p>But, to get out of the theoretical, let’s consider something more common in the real world, like the API response time scenario from my work at the ad analytics company.</p><h2 id="why-percentiles-are-better-than-averages-for-understanding-your-data">Why Percentiles Are Better Than Averages for Understanding Your Data</h2><p>We looked at how averages and percentiles are different—and now, we’re going to use a real-world scenario to demonstrate how using averages instead of percentiles can lead to false alarms or missed opportunities. </p><p>Why? Averages don’t always give you enough information to distinguish between real effects and outliers or noise, whereas percentiles can do a much better job.</p><p>Simply put, using averages can have a dramatic (and negative) impact on how values are reported, while percentiles can help you get closer to the “truth.”</p><p>If you’re looking at something like API response time, you’ll likely see a frequency distribution curve that looks something like this:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-6.jpg" class="kg-image" alt="A curve with frequency on the vertical axis and response time on the horizontal axis. The curve has a relatively sharp peak at the beginning labelled 250 ms, it then falls off quickly before shallowing out into a long tail" loading="lazy" width="1600" height="986" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-6.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-6.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-6.jpg 1600w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A frequency distribution for API response times with a peak at 250ms (all graphs are not to scale and are meant only for demonstration purposes).</span></figcaption></figure><p>In my former role at the ad analytics company, we’d aim for most of our API response calls to finish in under half a second, and many were much, much shorter than that. When we monitored our API response times, one of the most important things we tried to understand was how users were affected by changes in the code.  </p><p>Most of our API calls finished in under half a second, but some people used the system to get data over very long time periods or had odd configurations that meant their dashboards were a bit less responsive (though we tried to make sure those were rare!). </p><p>The type of curve that resulted is characterized as a <strong>long-tail distribution</strong> where we have a relatively large spike at 250 ms, with many of our values under that and then an exponentially decreasing number of longer response times.</p><p>We talked earlier about how, in symmetric curves (like the normal distribution), but a long-tail distribution is an<strong> asymmetric </strong>curve.</p><p>This means that the largest values are much larger than the middle values, while the smallest values aren’t that far from the middle values. (In the API monitoring case,  you can never have an API call that takes less than zero seconds to respond, but there’s no limit to how long they can take, so you get that long tail of longer API calls).</p><p>Thus,  the average and the median of a long-tail distribution start to diverge:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-7.jpg" class="kg-image" alt="The same curve as last time except now the median and average are labeled. The median is near the peak of the curve while the average is a bit rightward." loading="lazy" width="1600" height="986" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-7.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-7.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-7.jpg 1600w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">The API response time frequency curve with the median and average labeled. Graphs are not to scale and are meant for demonstration purposes only.</span></figcaption></figure><p>In this scenario, the average is significantly larger than the median because there are enough “large” values in the long tail to make the average larger. Conversely, in some other cases, the average might be smaller than the median. </p><p>But at the ad analytics company, we found that the average didn’t give us enough information to distinguish between important changes in how our API responded to software changes vs. noise/outliers that only affected a few individuals. </p><p>In one case, we introduced a change to the code that had a new query. The query worked fine in staging, but there was a lot more data in the production system. </p><p>Once the data was “warm” (in memory), it would run quickly, but it was very slow the first time. When the query went into production, the response time was well over a second for ~10% of the calls. </p><p>In our frequency curve, a response time over a second (but less than 10s) for ~10% of the calls resulted in a second, smaller hump in our frequency curve and looked like this:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-8.jpg" class="kg-image" alt="The same curve as last time except now there is a smaller hump further to the right of the long tail of the original graph, it’s approximately one fifth the height of the original and has approximately one tenth the area. The average and median have both shifted rightward, the average more than the median. The average is nearly inline with the second hump." loading="lazy" width="1600" height="986" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-8.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-8.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-8.jpg 1600w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A frequency curve showing the shift and extra hump that occurs when 10% of calls take a moderate amount of time, between 1 and 10s (graph still not to scale).</span></figcaption></figure><p>In this scenario, the average shifted a lot, while the median slightly shifted, it’s much less impacted.</p><p>You might think that this makes the average a better metric than the median because it helped us identify the problem (too long API response times), and we could set up our alerting to notify when the average shifts.</p><p>Let’s imagine that we’ve done that, and people will jump into action when the average goes above, say, 1 second(s).</p><p>But now, we have a few users who have started requesting 15 years of data from our UI...and those API calls take a <em>really long time</em>. This is because the API wasn’t really built to handle this “off-label” use.</p><p>Just a few calls from these users easily shifted the average way over our 1s threshold.</p><p>Why? The average (as a value) can be dramatically affected by outliers like this, even though they impact only a small fraction of our users. The average uses the sum of the data, so the magnitude of the outliers can have an outsized impact, whereas the median and other percentiles are based on the ordering of the data.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-9-1.jpg" class="kg-image" alt="The same curve without the second hump, but with a couple of hash marks on the x axis and some outliers far off to the right. These outliers are circled. The average has shifted far to the right, the same place it was with the hump but the median has remained in the same place as the original curve without hump or outliers." loading="lazy" width="2000" height="916" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-9-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-9-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2021/09/Graph-9-1.jpg 1600w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-9-1.jpg 2000w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">Our curve with a few outliers, where less than 1% of the API call responses are over 100s (the response time has a break representing the fact that the outliers would be way to the right otherwise, still, the graph is not to scale).</span></figcaption></figure><p><strong>The point is that the average doesn’t give us a good way to distinguish between outliers and real effects and can give odd results when we have a long-tail or asymmetric distribution.</strong></p><p>Why is this important to understand?</p><p>Well, in the first case, we had a problem affecting 10% of our API calls, which could be 10% or more of our users (how could it affect more than 10% of the users? Well, if a user makes 10 calls on average, and 10% of API calls are affected, then, on average, all the users would be affected... or at least some large percentage of them).</p><p>We want to respond very quickly to that type of urgent problem, affecting a large number of users. We built alerts and might even get our engineers up in the middle of the night and/or revert a change.</p><p>But the second case, where “off-label” user behavior or minor bugs had a large effect on a few API calls, was much more benign. Because relatively few users are affected by these outliers, we wouldn’t want to get our engineers up in the middle of the night or revert a change. (Outliers can still be important to identify and understand, both for understanding user needs or potential bugs in the code, but they usually <em>aren’t an emergency</em>).</p><p>Instead of using the average, we can instead use multiple percentiles to understand this type of behavior. Remember, unlike averages, percentiles rely on the <em>ordering</em> of the data rather than being impacted by the <em>magnitude</em> of data. If we use the 90th percentile, we <em>know</em> that 10% of users have values (API response times in our case) greater than it.   </p><p>Let’s look at the 90th percentile in our original graph; it nicely captures some of the long tail behavior:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-10.jpg" class="kg-image" alt="Back to the original graph with the median and average, except now the 90th percentile is also drawn in. The 90th percentile is further to the right than the median or average and is around the halfway point of the long tail portion of the curve." loading="lazy" width="1600" height="986" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-10.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-10.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-10.jpg 1600w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">Our original API response time graph showing the 90th percentile, median, and average. Graph not to scale.</span></figcaption></figure><p>When we have some outliers caused by a few users who’re running super long queries or a bug affecting a small group of queries, the average shifts, but the 90th percentile is hardly affected.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-11-1.jpg" class="kg-image" alt="Back to the graph with the outliers, except now the 90th percentile is there as well, it has remained in the same spot as the previous graph, but the average has shifted over to the right well beyond it. " loading="lazy" width="2000" height="916" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-11-1.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-11-1.jpg 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2021/09/Graph-11-1.jpg 1600w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-11-1.jpg 2000w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">Outliers affect the average but don’t impact the 90th percentile or median. (Graph is not to scale.)</span></figcaption></figure><p>But, when the tail is increased due to a problem affecting 10% of users, we see that the 90th percentile shifts outward pretty dramatically – which enables our team to be notified and respond appropriately:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/09/Graph-12.jpg" class="kg-image" alt="The same graph as the previous one with a smaller hump, except now the 90th percentile is on there as well, it has shifted to the right this time and is further right than the average." loading="lazy" width="1600" height="986" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/09/Graph-12.jpg 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2021/09/Graph-12.jpg 1000w, https://timescale.ghost.io/blog/content/images/2021/09/Graph-12.jpg 1600w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">But when there are “real” effects from responses that impact more than 10% of users, the 90th percentile shifts dramatically (Graph not to scale.)</span></figcaption></figure><p>This (hopefully) gives you a better sense of how and why percentiles can help you identify cases where large numbers of users are affected – but not burden you with false positives that might wake engineers up and give them alarm fatigue!</p><p>So, now that we know why we might want to use percentiles rather than averages, let’s talk about how we calculate them.</p><h2 id="how-percentiles-work-in-postgresql">How Percentiles Work in PostgreSQL</h2><p>To calculate any sort of exact percentile, you take <em>all</em> your values, sort them, then find the <em>n</em>th value based on the percentile you’re trying to calculate. </p><p>To see how this works in PostgreSQL, we’ll present a simplified case of our ad analytics company’s API tracking. </p><p>We’ll start off with a table like this:</p><pre><code class="language-SQL">CREATE TABLE responses(
	ts timestamptz, 
	response_time DOUBLE PRECISION);</code></pre><p>In PostgreSQL, we can calculate a percentile over the column <code>response_time</code> using the <a href="https://www.postgresql.org/docs/current/functions-aggregate.html#FUNCTIONS-ORDEREDSET-TABLE"><code>percentile_disc</code> aggregate</a>:</p><pre><code class="language-SQL">SELECT 
	percentile_disc(0.5) WITHIN GROUP (ORDER BY response_time) as median
FROM responses;</code></pre><p>This doesn’t look the same as a normal aggregate; the <code>WITHIN GROUP (ORDER BY …)</code> is a different syntax that works on special aggregates called <a href="https://www.postgresql.org/docs/13/xaggr.html#XAGGR-ORDERED-SET-AGGREGATES">ordered-set aggregates</a>.</p><p>Here, we pass in the percentile we want (0.5 or the 50th percentile for the median) to the <code>percentile_disc</code> function, and the column that we’re evaluating (<code>response_time</code>)  goes in the order by clause.</p><p>It will be more clear why this happens when we understand what’s going on under the hood. Percentiles give a guarantee that x percent of the data will fall below the value they return. To calculate that, we need to sort all of our data in a list and then pick out the value where 50% of the data falls below it and 50% falls above it.</p><p>For those of you who read the section of our previous post on <a href="https://timescale.ghost.io/blog/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design-2/#a-primer-on-postgresql-aggregation-through-pictures">how PostgreSQL aggregates work</a>, we discussed how an aggregate like <code>avg</code> works. </p><p>As it scans each row, the transition function updates some internal state (for <code>avg</code> it’s the <code>sum</code> and the <code>count</code>), and then a final function processes the internal state to produce a result (for <code>avg</code> divide <code>sum</code> by <code>count</code>).</p>
<!--kg-card-begin: html-->
    <video autoplay loop muted playsinline>
      <source id="player" src="https://s3.amazonaws.com/blog.timescale.com/gifs/hyperfunctions-3/avg_bar.mp4" type="video/mp4"></source>
    </video>
    <figcaption class="gif-caption">A GIF showing how the avg is calculated in PostgreSQL with the sum and count as the partial state as rows are processed and a final function that divides them when we’ve finished.
    </figcaption>
<!--kg-card-end: html-->
<p>The ordered set aggregates, like <code>percentile_disc</code>, work somewhat similarly, with one exception: instead of the state being a relatively small fixed-size data structure (like <code>sum</code> and <code>count</code> for <code>avg</code> ), it must keep all the values it has processed to sort them and calculate the percentile later. </p><p>Usually, PostgreSQL does this by putting the values into a data structure called a <a href="https://github.com/postgres/postgres/blob/c30f54ad732ca5c8762bb68bbe0f51de9137dd72/src/backend/utils/sort/tuplestore.c"><code>tuplestore</code></a> that stores and sorts values easily. </p><p>Then, when the final function is called, the <code>tuplestore</code> will first sort the data. Then, based on the value input into the <code>percentile_disc</code>), it will traverse to the correct point (0.5 of the way through the data for the median) in the sorted data and output the result.<br></p>
<!--kg-card-begin: html-->
    <video autoplay loop muted playsinline>
      <source id="player" src="https://s3.amazonaws.com/blog.timescale.com/gifs/hyperfunctions-3/percentile_disc.mp4" type="video/mp4"></source>
    </video>
    <figcaption class="gif-caption">With the percentile_disc ordered set aggregate, PostgreSQL has to store each value it sees in a tuplestore then when it’s processed all the rows, it sorts them, and then goes to the right point in the sorted list to extract the percentile we need. 
    </figcaption>
<!--kg-card-end: html-->
<p>Instead of performing these expensive calculations over very large data sets, <strong>many people find that approximate percentile calculations can provide a “close enough” approximation with significantly less work</strong>...which is why we introduced percentile approximation hyperfunctions.</p><h2 id="percentile-approximation-what-it-is-and-why-we-use-it-in-hyperfunctions">Percentile Approximation: What It Is and Why We Use It in Hyperfunctions</h2><p>In my experience, people often use averages and other summary statistics more frequently than percentiles because they are significantly “cheaper” to calculate over large datasets, both in computational resources and time.</p><p>As we noted above, calculating the average in PostgreSQL has a simple, two-valued aggregate state. Even if we calculate a few additional, related functions like the standard deviation, we still just need a small, fixed number of values to calculate the function.</p><p>In contrast, to calculate the percentile, we need all of the input values in a sorted list.</p><p>This leads to a few issues:</p><ol><li><strong>Memory footprint</strong>: The algorithm has to keep these values somewhere, which means keeping values in memory until they need to write some data to disk to avoid using too much memory (this is known as “spilling to disk”). This produces a significant memory burden and/or majorly slows down the operation because disk accesses are orders of magnitude slower than memory.</li><li><strong>Limited Benefits from Parallelization</strong>: Even though the algorithm can sort lists in parallel, the benefits from parallelization are limited because it still needs to merge all the sorted lists into a single, sorted list in order to calculate a percentile.</li><li><strong>High network costs: </strong>In distributed systems, all the values must be passed over the network to one node to be made into a single sorted list, which is slow and costly.</li><li><strong>No true partial states</strong>: Materialization of partial states (e.g., for continuous aggregates) is not useful because the partial state is simply all the values that underlie it. This could save on sorting the lists, but the storage burden would be high and the payoff low.</li><li><strong>No streaming algorithm</strong>: For streaming data, this is completely infeasible. You still need to maintain the full list of values (similar to the materialization of partial states problem above), which means that the algorithm essentially needs to store the entire stream!</li></ol><p>All of these can be manageable when you’re dealing with relatively small data sets, while for high volume, time-series workloads, they start to become more of an issue.</p><p>But, you only need the full list of values for calculating a percentile if you want <strong><em>exact</em></strong> percentiles. <strong>With relatively large datasets, you can often accept some accuracy tradeoffs to avoid running into any of these issues.</strong></p><p>The problems above, and the recognition of the tradeoffs involved in weighing whether to use averages or percentiles, led to the development of multiple algorithms to <a href="https://en.wikipedia.org/wiki/Quantile#Approximate_quantiles_from_a_stream">approximate percentiles in high volume systems.</a> Most percentile approximation approaches involve some sort of modified <a href="https://en.wikipedia.org/wiki/Histogram">histogram</a> to represent the overall shape of the data more compactly, while still capturing much of the shape of the distribution.</p><p>As we were designing hyperfunctions, we thought about how we could capture the benefits of percentiles (e.g., robustness to outliers, better correspondence with real-world impacts) while avoiding some of the pitfalls that come with calculating exact percentiles (above). </p><p>Percentile approximations seemed like the right fit for working with large, time-series datasets.</p><p>The result is a whole family of <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/">percentile approximation hyperfunctions</a>, built into TimescaleDB. The simplest way to call them is to use the <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/percentile_agg/"><code>percentile_agg</code> aggregate</a> along with the<a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/approx_percentile/"> <code>approx_percentile</code> accessor</a>.</p><p>This query calculates approximate 10th, 50th, and 90th percentiles:</p><pre><code class="language-SQL">SELECT 
    approx_percentile(0.1, percentile_agg(response_time)) as p10, 
    approx_percentile(0.5, percentile_agg(response_time)) as p50, 
    approx_percentile(0.9, percentile_agg(response_time)) as p90 
FROM responses;
</code></pre><p>(If you’d like to learn more about aggregates, accessors, and two-step aggregation design patterns, check out <a href="https://timescale.ghost.io/blog/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design-2/">our primer on PostgreSQL two-step aggregation</a>.) </p><p>These percentile approximations have many benefits when compared to the normal PostgreSQL exact percentiles, especially when used for large data sets.</p><h3 id="memory-footprint">Memory footprint</h3><p>When calculating percentiles over large data sets, our percentile approximations limit the memory footprint (or need to spill to disk, as described above). </p><p>Standard percentiles create memory pressure since they build up as much of the data set in memory as possible...and then slow down when forced to spill to disk.</p><p>Conversely, hyperfunctions’ percentile approximations have fixed-size representations based on the number of buckets in their modified histograms, so they limit the amount of memory required to calculate them.</p><p>Plus, all of our percentile approximation algorithms are parallelizable, so they can be computed using multiple workers in a single node; this can provide significant speedups because ordered-set aggregates like <code>percentile_disc</code> are not parallelizable in PostgreSQL. </p><h3 id="materialization-in-continuous-aggregates">Materialization in continuous aggregates</h3><p>TimescaleDB includes a feature called <a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/continuous-aggregates/">continuous aggregates</a>, designed to make queries on very large datasets run faster. </p><p>TimescaleDB continuous aggregates continuously and incrementally store the results of an aggregation query in the background, so when you run the query, only the data that has changed needs to be computed, not the entire dataset. </p><p>Unfortunately, exact percentiles using <code>percentile_disc</code> cannot be stored in continuous aggregates because they cannot be broken down into a partial form and would instead require storing the entire dataset inside the aggregate.</p><p>We designed our percentile approximation algorithms to be usable with continuous aggregates. They have fixed-size partial representations that can be stored and re-aggregated inside continuous aggregates. </p><p>This is a huge advantage compared to exact percentiles because now you can do things like baselining and alerting on longer periods without having to re-calculate from scratch every time. </p><p>Let’s go back to our API response time example and imagine we want to identify recent outliers to investigate potential problems.</p><p>One way to do that would be to look at everything that is, say, above the 99th percentile in the previous hour. </p><p>As a reminder, we have a table:</p><pre><code class="language-SQL">CREATE TABLE responses(
	ts timestamptz, 
	response_time DOUBLE PRECISION);
SELECT create_hypertable('responses', 'ts'); -- make it a hypertable so we can make continuous aggs</code></pre><p>First, we’ll create a one-hour aggregation:</p><pre><code class="language-SQL">CREATE MATERIALIZED VIEW responses_1h_agg
WITH (timescaledb.continuous)
AS SELECT 
    time_bucket('1 hour'::interval, ts) as bucket,
    percentile_agg(response_time)
FROM responses
GROUP BY time_bucket('1 hour'::interval, ts);</code></pre><p>Note that we don’t perform the accessor function in the continuous aggregate; we just perform the aggregation function. </p><p>Now, we can find the data in the last 30&nbsp;s greater than the 99th percentile like so:</p><pre><code class="language-SQL">SELECT * FROM responses 
WHERE ts &gt;= now()-'30s'::interval
AND response_time &gt; (
	SELECT approx_percentile(0.99, percentile_agg)
	FROM responses_1h_agg
	WHERE bucket = time_bucket('1 hour'::interval, now()-'1 hour'::interval)
);
</code></pre><p>At the ad analytics company, we had a lot of users, so we’d have tens or hundreds of thousands of API calls every hour. </p><p>By default, we have 200 buckets in our representation, so we’re getting a large reduction in the amount of data that we store and process by using a continuous aggregate. This means that it would speed up the response time significantly. If you don’t have as much data, you’ll want to increase the size of your buckets or decrease the fidelity of the approximation to achieve a large reduction in the data we have to process.</p><p>We mentioned that we only performed the aggregate step in the continuous aggregate view definition; we didn’t use our <code>approx_percentile</code> accessor function directly in the view. We do that because we want to be able to use other accessor functions and/or the  <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/rollup-percentile/"><u><code>rollup</code></u> function</a>, which you may remember as one of the main <a href="https://timescale.ghost.io/blog/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design-2/#why-we-use-the-two-step-aggregate-design-pattern">reasons we chose the two-step aggregate approach</a>.</p><p>Let’s look at how that works, we can create a daily rollup and get the 99th percentile like this:</p><pre><code class="language-SQL">SELECT 
	time_bucket('1 day', bucket),
	approx_percentile(0.99, rollup(percentile_agg)) as p_99_daily
FROM responses_1h_agg
GROUP BY 1;</code></pre><p>We could even use the <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/approx_percentile_rank/"><code>approx_percentile_rank</code></a> accessor function, which tells you what percentile a value would fall into.</p><p>Percentile rank is the inverse of the percentile function; in other words, if normally you ask, what is the value of <em>n</em>th percentile? The answer is a value.</p><p>With percentile rank, you ask what percentile would this value be in? The answer is a percentile.</p><p>So, using <code>approx_percentile_rank</code> allows us to see where the values that arrived in the last 5 minutes rank compared to values in the last day:</p><pre><code class="language-SQL">WITH last_day as (SELECT 
	time_bucket('1 day', bucket),
 	rollup(percentile_agg) as pct_daily
FROM foo_1h_agg
WHERE bucket &gt;= time_bucket('1 day', now()-'1 day'::interval)
GROUP BY 1)

SELECT approx_percentile_rank(response_time, pct_daily) as pct_rank_in_day
FROM responses, last_day
WHERE foo.ts &gt;= now()-'5 minutes'::interval;
</code></pre><p>This is another way continuous aggregates can be valuable.</p><p>We performed a <code>rollup</code> over a day, which just combined 24 partial states, rather than performing a full calculation over 24 hours of data with millions of data points.</p><p>We then used the <code>rollup</code> to see how that impacted just the last few minutes of data, giving us insight into how the last few minutes compare to the last 24 hours. These are just a few examples of how the percentile approximation hyperfunctions can give us some pretty nifty results and allow us to perform complex analysis relatively simply.</p><h2 id="percentile-approximation-deep-dive">Percentile Approximation Deep Dive</h2><p>Some of you may be wondering how TimescaleDB hyperfunctions’ underlying algorithms work, so let’s dive in! (For those of you who don’t want to get into the weeds, feel free to skip over this bit.)</p><h3 id="approximation-methods-and-how-they-work">Approximation methods and how they work</h3><p>We implemented two different percentile approximation algorithms as TimescaleDB hyperfunctions: <a href="https://arxiv.org/pdf/2004.08604.pdf">UDDSketch</a> and <a href="https://github.com/tdunning/t-digest">T-Digest</a>. Each is useful in different scenarios, but first, let’s understand some of the basics of how they work. </p><p>Both use a modified histogram to approximate the shape of a distribution. A histogram buckets nearby values into a group and tracks their frequency.</p><p>You often see a histogram plotted like so:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--1--2.png" class="kg-image" alt="A graph similar to the previous graphs of the response time of an API, except now the curve has been replaced by a series of black line graph boxes representing the buckets of a histogram." loading="lazy" width="2000" height="821" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/pasted-image-0--1--2.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/pasted-image-0--1--2.png 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2022/01/pasted-image-0--1--2.png 1600w, https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--1--2.png 2048w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A histogram representing the same data as our response time frequency curve above, you can see how the shape of the graph is similar to the frequency curve. Not to scale.</span></figcaption></figure><p>If you compare this to the frequency curve we showed above, you can see how this could provide a reasonable approximation of the  API response time vs frequency response. Essentially, a histogram has a series of bucket boundaries and a count of the number of values that fall within each bucket.</p><p>To calculate the approximate percentile for, say, the 20th percentile, you first consider the fraction of your total data that would represent it. For our 20th percentile, that would be 0.2 * <code>total_points</code>.</p><p>Once you have that value, you can then sum the frequencies in each bucket, left to right, to find at which bucket you get the value closest to 0.2 * <code>total_points</code>. </p><p>You can even interpolate between buckets to get more exact approximations when the bucket spans a percentile of interest. </p><p>When you think of a histogram, you may think of one that looks like the one above, where the buckets are all the same width. </p><p>But choosing the bucket width, especially for widely varying data, can get very difficult or lead you to store a lot of extra data. </p><p>In our API response time example, we could have data spanning from tens of milliseconds up to ten seconds or hundreds of seconds. </p><p>This means that the right bucket size for a good approximation of the 1st percentile, e.g., 2ms, would be WAY smaller than necessary for a good approximation of the 99th percentile.</p><p>This is why most percentile approximation algorithms use a modified histogram with a <em>variable bucket width</em>. </p><p>For instance, the UDDSketch algorithm uses logarithmically sized buckets, which might look something like this:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0-6.png" class="kg-image" alt="A graph similar to the last one except the black boxes start smaller than the previous ones and increase in width as you move to the right." loading="lazy" width="2000" height="828" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/pasted-image-0-6.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/pasted-image-0-6.png 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2022/01/pasted-image-0-6.png 1600w, https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0-6.png 2048w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A modified histogram showing how logarithmic buckets like the UDDSketch algorithm uses can still represent the data. (Note: we’d need to modify the plot to plot the frequency/bucket width so that the scale would remain similar; however, this is just for demonstration purposes and not drawn to scale).</span></figcaption></figure><p>The designers of UDDSketch used a logarithmic bucket size like this because what they care about is the <em>relative error</em>.</p>
<!--kg-card-begin: html-->
<p>For reference, absolute error is defined as the difference between the actual and the approximated value:
\begin{equation}
\text{err}_\text{absolute} = abs(v_\text{actual} - v_\text{approx})
\end{equation}
   </p>
<!--kg-card-end: html-->

<!--kg-card-begin: html-->
<p>To get relative error, you divide the absolute error by the value:
    \begin{equation}
\text{err}_\text{relative} = \frac{\text{err}_\text{absolute}}{   v_\text{actual}}
\end{equation}
</p>
<!--kg-card-end: html-->
<p>If we had a constant absolute error, we might run into a situation like the following: </p><p>We ask for the 99th percentile, and the algorithm tells us it’s 10s +/- 100ms. Then, we ask for the 1st percentile, and the algorithm tells us it’s 10ms +/- 100ms.</p><p>The error for the 1st percentile is way too high!</p><p>If we have a constant relative error, then we’d get 10ms +/- 100 microseconds. </p><p>This is much, much more useful. (And 10s +/- 100 microseconds is probably too tight, we likely don’t really care about 100 microseconds if we’re already at 10s.)</p><p>This is why the UDDSketch algorithm uses logarithmically sized buckets, where the width of the bucket scales with the size of the underlying data. This allows the algorithm to provide constant relative error across the full range of percentiles. </p>
<!--kg-card-begin: html-->
<p>As a result, you always know that the true value of the percentile will fall within some range \([v_\text{approx} (1-err), v_\text{approx} (1+err)]\)</p>
<!--kg-card-end: html-->
<p>On the other hand, T-Digest uses buckets that are variably sized, based on where they fall in the distribution. Specifically, it uses smaller buckets at the extremes of the distribution and larger buckets in the middle.</p><p>So, it might look something like this:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--2--1.png" class="kg-image" alt="A graph similar to the previous two except now the black boxes start smaller than the first, increase in width towards the center and then decrease in width as you move to the right edge." loading="lazy" width="2000" height="867" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/pasted-image-0--2--1.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/pasted-image-0--2--1.png 1000w, https://timescale.ghost.io/blog/content/images/size/w1600/2022/01/pasted-image-0--2--1.png 1600w, https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--2--1.png 2048w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">A modified histogram showing how variably sized buckets that are smaller at the extremes, like what the TDigest algorithm uses, can still represent the data (Note: for illustration purposes, not to scale.)</span></figcaption></figure><p>This histogram structure with variable-sized buckets optimizes for different things than UDDSketch. Specifically, it takes advantage of the idea that when you’re trying to understand the distribution, you likely care more about fine distinctions between extreme values than about the middle of the range. </p><p>For example, I usually care a lot about distinguishing the 5th percentile from the 1st or the 95th from the 99th, while I don’t care as much about distinguishing between the 50th and the 55th percentile.</p><p>The distinctions in the middle are less meaningful and interesting than the distinctions at the extremes. (Caveat: the TDigest algorithm is a bit more complex than this, and this doesn’t completely capture its behavior, but we’re trying to give a general gist of what’s going on. If you want more information, <a href="https://arxiv.org/abs/1902.04023">we recommend this paper</a>).</p><h3 id="using-advanced-approximation-methods-in-timescaledb-hyperfunctions">Using advanced approximation methods in TimescaleDB hyperfunctions</h3><p>So far in this post, we’ve only used the general-purpose <code>percentile_agg</code> aggregate. It uses the UDDSketch algorithm under the hood and is a good starting point for most users.</p><p>We’ve also provided separate <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/percentile-aggregation-methods/uddsketch/"><code>uddsketch</code></a>  and <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/percentile-aggregation-methods/tdigest/"><code>tdigest</code></a> aggregates to allow for more customizability.</p><p>Each takes the number of buckets as their first argument (which determines the size of the internal data structure) and <code>uddsketch</code> also has an argument for the target maximum relative error. </p><p>We can use the normal <code>approx_percentile</code> accessor function  just as we used with <code>percentile_agg</code>, so, we could compare median estimations like so:</p><pre><code class="language-SQL">SELECT 
	approx_percentile(0.5, uddsketch(200, 0.001, response_time)) as median_udd,
	approx_percentile(0.5, tdigest(200, response_time)) as median_tdig
FROM responses;</code></pre><p>Both of them also work with the <code>approx_percentile_rank</code> hyperfunction we discussed above. </p><p>If we wanted to see where 1000 would fall in our distribution, we could do something like this:</p><pre><code class="language-SQL">SELECT 
	approx_percentile_rank(1000, uddsketch(200, 0.001, response_time)) as rnk_udd,
	approx_percentile_rank(1000, tdigest(200, response_time)) as rnk_tdig
FROM responses;</code></pre><p>In addition, each of the approximations has some accessors that only work with their items based on the approximation structure.</p><p>For instance, <code>uddsketch</code> provides an <code>error</code> accessor function. This will tell you the actual guaranteed maximum relative error based on the values that the <code>uddsketch</code> saw.</p><p>The UDDSketch algorithm guarantees a maximum relative error, while the T-Digest algorithm does not, so <code>error</code> only works with <code>uddsketch</code> (and <code>percentile_agg</code> because it uses <code>uddsketch</code> algorithm under the hood).</p><p>This error guarantee is one of the main reasons we chose it as the default because error guarantees are useful for determining whether you’re getting a good approximation.</p><p><code>Tdigest</code>, on the other hand, provides <code>min_val</code> &amp; <code>max_val</code> accessor functions because it biases its buckets to the extremes and can provide the exact min and max values at no extra cost. <code>Uddsketch</code> can’t provide that.</p><p>You can call these other accessors like so:</p><pre><code class="language-SQL">SELECT 
	approx_percentile(0.5, uddsketch(200, 0.001, response_time)) as median_udd,
	error(uddsketch(200, 0.001, response_time)) as error_udd,
	approx_percentile(0.5, tdigest(200, response_time)) as median_tdig,
	min_val(tdigest(200, response_time)) as min,
	max_val(tdigest(200, response_time)) as max
FROM responses;</code></pre><p>As we discussed in the last post about <a href="https://timescale.ghost.io/blog/blog/how-postgresql-aggregation-works-and-how-it-inspired-our-hyperfunctions-design-2/#why-we-use-the-two-step-aggregate-design-pattern">two-step aggregates</a>, calls to all of these aggregates are automatically deduplicated and optimized by PostgreSQL so that you can call multiple accessors with minimal extra cost. </p><p>They also both have <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/rollup-percentile/"><code>rollup</code></a>  functions defined for them, so you can re-aggregate when they’re used in continuous aggregates or regular queries. </p><p>(Note: <code>tdigest</code> rollup can introduce some additional error or differences compared to calling the <code>tdigest</code> on the underlying data directly. In most cases, this should be negligible and would often be comparable to changing the order in which the underlying data was ingested.)</p><p>We’ve provided a few of the tradeoffs and differences between the algorithms here, but we have a <a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/percentile-aggregation-methods/#choosing-the-right-algorithm-for-your-use-case">longer discussion in the docs that can help you choose</a>. You can also start with the default <code>percentile_agg</code> and then experiment with different algorithms and parameters on your data to see what works best for your application.</p><h2 id="wrapping-it-up">Wrapping It Up</h2><p>We’ve provided a brief overview of percentiles, how they can be more informative than more common statistical aggregates like average, why percentile approximations exist, and a little bit of how they generally work within TimescaleDB hyperfunctions.</p><p><strong>If you’d like to get started with the </strong><a href="https://docs.timescale.com/api/latest/hyperfunctions/percentile-approximation/"><strong>percentile approximation hyperfunctions</strong></a><strong>—and many more—right away, spin up a fully managed Timescale Cloud service</strong>: create an account to <a href="https://console.cloud.timescale.com/signup">try it for free</a> for 30 days. (Hyperfunctions are pre-loaded on each new cloud database service on Timescale, so after you create a new service, you’re all set to use them).</p><p><strong>If you prefer to manage your own database instances, you can </strong><a href="https://github.com/timescale/timescaledb-toolkit"><strong>download and install the <code>timescaledb_toolkit</code> extension</strong></a> on GitHub, after which you’ll be able to use percentile approximation and other hyperfunctions.</p><p>We believe time-series data is everywhere, and making sense of it is crucial for all manner of technical problems. We built hyperfunctions to make it easier for developers to harness the power of time-series data. </p><p>We’re always looking for feedback on what to build next and would love to know how you’re using hyperfunctions, problems you want to solve, or things you think should—or could—be simplified to make analyzing time-series data in SQL that much better. (To contribute feedback, comment on an <a href="https://github.com/timescale/timescaledb-toolkit/issues">open issue</a> or in a <a href="https://github.com/timescale/timescaledb-toolkit/discussions">discussion thread</a> in GitHub.)</p><h2 id="faqs">FAQs</h2><h3 id="why-are-percentiles-better-than-averages-for-understanding-data">Why are percentiles better than averages for understanding data?</h3><p>Percentiles are more robust to outliers than averages. This is especially true for asymmetric distributions like API response times.&nbsp;</p><p>While an average can be dramatically skewed by a few extreme values (like API calls taking 100+ seconds), percentiles like the 90th percentile only shift when a significant portion of the data changes.&nbsp;</p><p>For example: if 10&nbsp;% of API calls slow down from 250&nbsp;ms to 5 seconds, the 90th percentile will clearly show this problem, while outliers from just a few users won't trigger false alarms.</p><h3 id="how-do-percentile-approximations-work-in-timescaledb">How do percentile approximations work in TimescaleDB?</h3><p>TimescaleDB's percentile approximation hyperfunctions use modified histograms to represent data distribution more compactly while maintaining accuracy.&nbsp;</p><p>These approximations use either UDDSketch (the default) with logarithmically sized buckets or T-Digest with variable-sized buckets that are smaller at distribution extremes.&nbsp;</p><p>You can calculate approximate percentiles using syntax like <code>SELECT approx_percentile(0.9, percentile_agg(response_time)) as p90 FROM responses;</code></p><p>This syntax will use significantly less memory and computation than exact percentiles.</p><h3 id="what-are-the-benefits-of-using-percentile-approximations-for-large-datasets">What are the benefits of using percentile approximations for large datasets?</h3><p>Percentile approximations have a fixed memory footprint regardless of dataset size, unlike exact percentiles, which must store all values.&nbsp;</p><p>They’re parallelizable for faster computation and can be used with continuous aggregates for incremental calculation—all while still providing accurate insights with configurable error bounds.&nbsp;</p><p>For example, let’s say you’re tracking hourly API response times using a continuous aggregate with percentile approximations. This method allows you to instantly identify recent outliers compared to historical patterns without recalculating from raw data.</p><h3 id="how-do-i-choose-between-uddsketch-and-t-digest-algorithms">How do I choose between UDDSketch and T-Digest algorithms?</h3><p>UDDSketch (the default in <code>percentile_agg</code>) guarantees a maximum relative error across all percentiles. It’s ideal when you need consistent accuracy across your distribution.&nbsp;</p><p>T-Digest optimizes for accuracy at the extremes of your distribution, making it better when you care more about precisely measuring the 1st or 99th percentiles than the middle ranges.&nbsp;</p><p>You can compare both approaches using <code>SELECT approx_percentile(0.5, uddsketch(200, 0.001, response_time)) as median_udd, approx_percentile(0.5, tdigest(200, response_time)) as median_tdig FROM responses;</code></p><h3 id="how-can-i-use-percentile-approximations-with-continuous-aggregates">How can I use percentile approximations with continuous aggregates?</h3><p>Continuous aggregates allow you to precompute and incrementally update percentile approximations, significantly improving query performance.&nbsp;</p><p><strong>Step 1</strong>: Create a continuous aggregate that stores just the percentile approximation state: <code>CREATE MATERIALIZED VIEW responses_1h_agg WITH (timescaledb.continuous) AS SELECT time_bucket('1 hour'::interval, ts) as bucket, percentile_agg(response_time) FROM responses GROUP BY 1;&nbsp;</code></p><p><strong>Step 2</strong>: Query it using accessor functions like <code>approx_percentile(0.99, percentile_agg)</code> or combine multiple time buckets with the rollup function to analyze trends across different time periods.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Time-Weighted Averages Are and Why You Should Care]]></title>
            <description><![CDATA[Learn how time-weighted averages are calculated and why they’re so powerful for data analysis.]]></description>
            <link>https://www.tigerdata.com/blog/what-time-weighted-averages-are-and-why-you-should-care</link>
            <guid isPermaLink="true">https://www.tigerdata.com/blog/what-time-weighted-averages-are-and-why-you-should-care</guid>
            <category><![CDATA[Engineering]]></category>
            <category><![CDATA[General]]></category>
            <category><![CDATA[PostgreSQL]]></category>
            <dc:creator><![CDATA[David Kohn]]></dc:creator>
            <pubDate>Thu, 22 Jul 2021 13:04:23 GMT</pubDate>
            <media:content medium="image" href="https://timescale.ghost.io/blog/content/images/2021/07/national-cancer-institute-zz_3tCcrk7o-unsplash--1-.jpg">
            </media:content>
            <content:encoded><![CDATA[<p>Many people who work with time-series data have nice, regularly sampled datasets. Data could be sampled every few seconds, or milliseconds, or whatever they choose, but by regularly sampled, we mean the time between data points is basically constant. Computing the average value of data points over a specified time period in a regular dataset is a relatively well-understood query to compose. </p><p>But for those who don't have regularly sampled data, getting a representative average over a period of time can be a complex and time-consuming query to write. <strong>Time-weighted averages are a way to get an unbiased average when you are working with irregularly sampled data</strong>.</p><p>Time-series data comes at you fast, sometimes generating millions of data points per second (<a href="https://timescale.ghost.io/blog/blog/what-the-heck-is-time-series-data-and-why-do-i-need-a-time-series-database-dcf3b1b18563/">read more about time-series data</a>). Because of the sheer volume and rate of information, time-series data can already be complex to query and analyze, which is why we built TimescaleDB, a petabyte-scale, relational database for <a href="https://www.tigerdata.com/blog/time-series-introduction" rel="noreferrer">time series</a>.</p><p>Irregularly sampled time-series data just adds another level of complexity – and is more common than you may think. For example, irregularly sampled data, and thus the need for time-weighted averages, frequently occurs in:</p><ul><li><strong>Industrial IoT</strong>, where teams “compress” data by only sending points when the value changes</li><li><strong>Remote sensing</strong>, where sending data back from the edge can be costly, so you only send high-frequency data for the most critical operations</li><li><strong>Trigger-based systems</strong>, where the sampling rate of one sensor is affected by the reading of another (i.e., a security system that sends data more frequently when a motion sensor is triggered)</li><li>...and many, many more</li></ul><p>At Timescale, we’re always looking for ways to make developers’ lives easier, especially when they’re working with time-series data. To this end, <a href="https://timescale.ghost.io/blog/blog/introducing-hyperfunctions-new-sql-functions-to-simplify-working-with-time-series-data-in-postgresql/">we introduced hyperfunctions</a>, new SQL functions that simplify working with time-series data in PostgreSQL. <strong>One of these hyperfunctions enables you to </strong><a href="https://docs.timescale.com/api/latest/hyperfunctions/time-weighted-averages/#time-weighted-average-functions"><strong>compute time-weighted averages</strong></a><strong> quickly and efficiently</strong>, so you gain hours of productivity.</p><p><br>Read on for examples of time-weighted averages, how they’re calculated, how to use the time-weighted averages hyperfunctions in TimescaleDB, and some ideas for how you can use them to get a productivity boost for your projects, no matter the domain.</p><p><strong>If you’d like to get started with the <code>time_weight</code> hyperfunction—and many more—right away, spin up a fully managed Timescale service</strong>: create an account to <a href="https://console.cloud.timescale.com/signup">try it for free</a> for 30 days. Hyperfunctions are pre-loaded on each new database service on Timescale, so after you create a new service, you’re all set to use them.</p><p><strong>If you prefer to manage your own database instances, you can </strong><a href="https://github.com/timescale/timescaledb-toolkit"><strong>download and install the timescaledb_toolkit extension</strong></a> on GitHub, after which you’ll be able to use <code>time_weight</code> and other hyperfunctions.</p><p>Finally, we love building in public and continually improving:</p><ul><li>If you have questions or comments on this blog post, <a href="https://github.com/timescale/timescaledb-toolkit/discussions/185">we’ve started a discussion on our GitHub page, and we’d love to hear from you</a>. (And, if you like what you see, GitHub ⭐ are always welcome and appreciated too!)</li><li>You can view our <a href="https://github.com/timescale/timescaledb-toolkit">upcoming roadmap on GitHub</a> for a list of proposed features, as well as features we’re currently implementing and those that are available to use today.</li></ul><h2 id="what-are-time-weighted-averages">What are time-weighted averages?</h2>
<p>I’ve been a developer at Timescale for over 3 years and worked in databases for about 5 years, but I was an electrochemist before that. As an electrochemist, I worked for a battery manufacturer and saw a lot of charts like these:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/image.png" class="kg-image" alt="Battery discharge curve showing cell voltage on the y-axis and capacity in amp-hours on the x-axis. The curve starts high, decreases relatively rapidly through the exponential zone, then stays relatively constant for a long period through the nominal zone, after which the voltage drops quite rapidly as it reaches its fully discharged state. " loading="lazy" width="744" height="426" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/image.png 600w, https://timescale.ghost.io/blog/content/images/2021/08/image.png 744w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">Example battery discharge curve, which describes how long a battery can power something. (Also a prime example of where time-weighted averages are 💯 necessary) Derived from </em></i><a href="https://www.nrel.gov/docs/fy17osti/67809.pdf"><i><em class="italic" style="white-space: pre-wrap;">https://www.nrel.gov/docs/fy17osti/67809.pdf</em></i></a></figcaption></figure><p>That’s a battery discharge curve, which describes how long a battery can power something. The x-axis shows capacity in Amp-hours, and since this is a constant current discharge, the x-axis is really just a proxy for time. The y-axis displays voltage, which determines the battery’s power output; as you continue to discharge the battery, the voltage drops until it gets to a point where it needs to be recharged.</p><p>When we’d do R&amp;D for new battery formulations, we’d cycle many batteries many times to figure out which formulations make batteries last the longest. </p><p>If you look more closely at the discharge curve, you’ll notice that there are only two “interesting” sections:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/image-1.png" class="kg-image" alt="The same battery discharge curve as in the previous image but with the “interesting bits” circled, namely where the voltage decreases rapidly at the beginning and the end of the discharge curve. " loading="lazy" width="757" height="447" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/image-1.png 600w, https://timescale.ghost.io/blog/content/images/2021/08/image-1.png 757w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">Example battery discharge curve, calling out the “interesting bits” (the points in time where data changes rapidly)</em></i></figcaption></figure><p>These are the parts at the beginning and end of the discharge where the voltage changes rapidly. Between these two sections, there’s that long period in the middle, where the voltage hardly changes at all:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/image-2.png" class="kg-image" alt="The same battery discharge curve again, except now the “boring” part of the curve is highlighted, which is the middle section where the voltage hardly changes." loading="lazy" width="749" height="449" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/image-2.png 600w, https://timescale.ghost.io/blog/content/images/2021/08/image-2.png 749w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">Example battery discharge curve, calling out the “boring bits” (the points in time where the data remains fairly constant)</em></i></figcaption></figure><p>Now, when I said before that I was an electrochemist, I will admit that I was exaggerating a little bit. I knew enough about electrochemistry to be dangerous, but I worked with folks with PhDs who knew <em>a lot</em> more than I did. </p><p>But, I was often better than them at working with data, so I’d do things like programming the <a href="https://en.wikipedia.org/wiki/Potentiostat">potentiostat</a>, the piece of equipment you hook the battery up to in order to perform these tests. </p><p>For the interesting parts of the discharge cycle (those parts at the start and end), we could have the potentiostat sample at its max rate, usually a point every 10 milliseconds or so. We didn’t want to sample as many data points during the long, boring parts where the voltage didn’t change because it would mean saving lots of data with unchanging values and wasting storage.</p><p>To reduce the boring data we’d have to deal with without losing the interesting bits, we’d set up the program to sample every 3 minutes, or when the voltage changed by a reasonable amount, say more than 5 mV. </p><p>In practice, what would happen is something like this:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/image-3.png" class="kg-image" alt="The same battery discharge curve again, this time with data points superimposed on the image. The data points are spaced close together in the “interesting bits,” where the voltage changes quickly at the beginning and end of the discharge curve. The data points are spaced further apart during the “boring” part in the middle, where the voltage hardly changes at all. " loading="lazy" width="755" height="403" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/image-3.png 600w, https://timescale.ghost.io/blog/content/images/2021/08/image-3.png 755w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">Example battery discharge curve with data points superimposed to depict rapid sampling during the interesting bits and slower sampling during the boring bits.</em></i></figcaption></figure><p>By sampling the data in this way, we'd get more data during the interesting parts and less data during the boring middle section. That’s great!</p><p>It let us answer more interesting questions about the quickly changing parts of the curve and gave us all the information we needed about the slowly changing sections – without storing gobs of redundant data.<strong> But, here’s a question: given this dataset, how do we find the average voltage during the discharge?</strong></p><p>That question is important because it was one of the things we could compare between this discharge curve and future ones, say 10 or 100 cycles later. As a battery ages, its average voltage drops, and how much it dropped over time could tell us how well the battery’s storage capacity held up during its lifecycle – and if it could turn into a useful product. </p><p>The problem is that the data in the interesting bits are sampled more frequently (i.e., there are more data points for the interesting bits), which would give it more weight when calculating the average, even though it shouldn't.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2021/08/image-4.png" class="kg-image" alt="The same battery curve again, with the same data points superimposed and the “interesting bits” circled again, however this time noting that the “interesting bits” shouldn’t count extra even though there are more data points included in the circled area." loading="lazy" width="754" height="449" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2021/08/image-4.png 600w, https://timescale.ghost.io/blog/content/images/2021/08/image-4.png 754w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">Example battery discharge curve, with illustrative data points to show that while we collect more data during the interesting bits, they shouldn’t count “extra.”</em></i></figcaption></figure><p>If we just took a naive average over the whole curve, adding the value at each point and dividing by the number of points, it would mean that a change to our sampling rate could change our calculated average...even though the underlying effect was really the same! </p><p>We could easily overlook any of the differences we were trying to identify – and any clues about how we could improve the batteries could just get lost in the variation of our sampling protocol. </p><p>Now, some people will say: well, why not just sample at max rate of the potentiostat, even during the boring parts? Well, these discharge tests ran <em>really</em> long. They’d take 10 to 12 hours to complete, but the interesting bits could be pretty short, from seconds or minutes. If we sampled at the highest rate, one every 10ms or so, it would mean orders of magnitude more data to store even though we would hardly use any of it! And orders of magnitude more data would mean more cost, more time for analysis, all sorts of problems.</p><p>So the big question is: <strong>how do we get a representative average when we’re working with irregularly spaced data points?</strong></p><p>Let’s get theoretical for a moment here:</p><p>(This next bit is a little equation-heavy, but I think they’re<em> relatively</em> simple equations, and they map very well onto their graphical representation. I always like it when folks give me the math and graphical intuition behind the calculations – but if you want to skip ahead to just see how time-weighted average is used, the mathy bits end <a href="https://timescale.ghost.io/blog/blog/what-time-weighted-averages-are-and-why-you-should-care/#how-to-compute-time-weighted-averages-in-sql">here</a>.)</p><h2 id="mathy-bits-how-to-derive-a-time-weighted-average">Mathy Bits: How to derive a time-weighted average</h2>
<p>Let’s say we have some points like this:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0-11.png" class="kg-image" alt="A graph showing value on the y-axis and time on the x-axis. There are four points:  open parens t 1 comma v 1 close parens to open parens t 4 comma  v 4 close parens spaced unevenly in time on the graph. " loading="lazy" width="1380" height="1144" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/pasted-image-0-11.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/pasted-image-0-11.png 1000w, https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0-11.png 1380w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">A theoretical, irregularly sampled time-series dataset</em></i></figcaption></figure><p>Then, the normal average would be the sum of the values, divided by the total number of points:</p><p>\begin{equation} avg = \frac{(v_1 + v_2 + v_3 + v_4)}{4}  \end{equation}</p>
<p>But, because they’re irregularly spaced, we need some way to account for that. </p><p>One way to think about it would be to get a value at every point in time, and then divide it by the total amount of time. This would be like getting the total area under the curve and dividing by the total amount of time ΔT.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--3-.png" class="kg-image" alt="The same graph as above but with the area under the curve shaded in gray. The area under the curve is drawn by drawing a line through each pair of points and then shading down to the x-axis. The total time spanned by the points from t 1 to t 4 is denoted as Delta T." loading="lazy" width="1348" height="1122" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/pasted-image-0--3-.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/pasted-image-0--3-.png 1000w, https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--3-.png 1348w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">The area under an irregularly sampled time-series dataset</em></i></figcaption></figure><p>\begin{equation} better\_avg = \frac{area\_under\_curve}{\Delta T}  \end{equation}</p>
<p>(In this case, we’re doing a linear interpolation between the points). So, let’s focus on finding that area. The area between the first two points is a trapezoid:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--1--6.png" class="kg-image" alt="The same graph as above, except there is a trapezoid shaded in blue bounded on top by the line connecting the first two points and vertical lines connecting the points to the x-axis. The distance between the two points on the x-axis is denoted delta t 1." loading="lazy" width="1182" height="1008" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/pasted-image-0--1--6.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/pasted-image-0--1--6.png 1000w, https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--1--6.png 1182w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">A trapezoid representing the area under the first two points</em></i></figcaption></figure><p>Which is really a rectangle plus a triangle:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--4-.png" class="kg-image" alt="The same graph as the previous, except now the trapezoid, has been divided into a rectangle and a triangle. The rectangle is the height of the first point v 1. The triangle is a right triangle with the line connecting the first two points as the hypotenuse. The distance on the y-axis between the first two points is denoted as delta v 1. " loading="lazy" width="1180" height="972" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/pasted-image-0--4-.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/pasted-image-0--4-.png 1000w, https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--4-.png 1180w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">That same trapezoid broken down into a rectangle and a triangle.</em></i></figcaption></figure><p>Okay, let’s calculate that area:</p><p>\begin{equation} area = \Delta t_1 v_1 + \frac{\Delta t_1 \Delta v_1}{2}  \end{equation}</p>
<p>So just to be clear, that’s:</p><math xmlns="http://www.w3.org/1998/Math/MathML" display="block">
  <semantics>
    <mrow>
      <mi>a</mi>
      <mi>r</mi>
      <mi>e</mi>
      <mi>a</mi>
      <mo>=</mo>
      <munder>
        <mrow data-mjx-texclass="OP">
          <munder>
            <mrow>
              <mi mathvariant="normal">Δ</mi>
              <msub>
                <mi>t</mi>
                <mn>1</mn>
              </msub>
              <msub>
                <mi>v</mi>
                <mn>1</mn>
              </msub>
            </mrow>
            <mo>⏟</mo>
          </munder>
        </mrow>
        <mtext>area of rectangle</mtext>
      </munder>
      <mo>+</mo>
      <munder>
        <mrow data-mjx-texclass="OP">
          <munder>
            <mfrac>
              <mrow>
                <mi mathvariant="normal">Δ</mi>
                <msub>
                  <mi>t</mi>
                  <mn>1</mn>
                </msub>
                <mi mathvariant="normal">Δ</mi>
                <msub>
                  <mi>v</mi>
                  <mn>1</mn>
                </msub>
              </mrow>
              <mn>2</mn>
            </mfrac>
            <mo>⏟</mo>
          </munder>
        </mrow>
        <mtext>area of triangle</mtext>
      </munder>
    </mrow>
    <annotation encoding="application/x-tex">\begin{equation} area = \underbrace{\Delta t_1 v_1}_\text{area of rectangle} + \underbrace{\frac{\Delta t_1 \Delta v_1}{2}}_\text{area of triangle}  \end{equation}</annotation>
  </semantics>
</math><p>Okay. So now if we notice that:</p><p>\begin{equation} \Delta v_1 = v_2 - v_1      \end{equation}</p>
<p>We can simplify this equation pretty nicely:</p><p>Start with:<br>
\begin{equation} \Delta t_1 v_1 + \frac{\Delta t_1 (v_2 - v_1)}{2}  \end{equation}</p>
<p>Factor out: \begin{equation}(\frac{\Delta t_1}{2} ) \end{equation}</p>
<p>\begin{equation}  \frac{\Delta t_1}{2} (2v_1 + (v_2 - v_1))    \end{equation}</p>
<p>Simplify:<br>
\begin{equation}  \frac{\Delta t_1}{2} (v_1 + v_2)    \end{equation}</p>
<p>One cool thing to note is that this gives us a new way to think about this solution: it’s the average of each pair of adjacent values, weighted by the time between them:</p><p>\begin{equation}  area = \underbrace{\frac{(v_1 + v_2)}{2}}_{\text{average of    } v_1 \text{ &amp; } v_2} \Delta t_1   \end{equation}</p>
<p>It’s also equal to the area of the rectangle drawn to the midpoint between v1 and v2:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--2--2.png" class="kg-image" alt="The same graph as the previous, except that now there is a rectangle imposed on the trapezoid. The rectangle is the same width as the others and goes to a height of v 1 plus v 2 over 2. " loading="lazy" width="1198" height="948" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/pasted-image-0--2--2.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/pasted-image-0--2--2.png 1000w, https://timescale.ghost.io/blog/content/images/2022/01/pasted-image-0--2--2.png 1198w" sizes="(min-width: 720px) 720px"><figcaption><i><em class="italic" style="white-space: pre-wrap;">The area of the trapezoid and of the rectangle, drawn to the midpoint between the two points, is the same.</em></i></figcaption></figure><p>Now that we’ve derived the formula for two adjacent points, we can repeat this for every pair of adjacent points in the dataset. Then all we need to do is sum that up, and that will be the time-weighted sum, which is equal to the area under the curve. (Folks who have studied calculus may actually remember some of this from when they were learning about integrals and integral approximations!) </p><p>With the total area under the curve calculated,  all we have to do is divide the time-weighted sum by the overall  ΔT and we have our time-weighted average. 💥</p><p>Now that we've worked through our time-weighted average in theory, let’s test it out in SQL.</p><h2 id="how-to-compute-time-weighted-averages-in-sql">How to compute time-weighted averages in SQL</h2>
<p>Let’s consider the scenario of an ice cream manufacturer or shop owner who is monitoring their freezers. It turns out that ice cream needs to stay in a relatively narrow range of temperatures (~0-10℉)<sup class="footnote-ref"><a href="#fn1" id="fnref1">[1]</a></sup> so that it doesn’t melt and re-freeze, causing those weird crystals that no one likes. Similarly, if ice cream gets too cold, it’s too hard to scoop.</p>
<p>The air temperature in the freezer will vary a bit more dramatically as folks open and close the door, but the ice cream temperature takes longer to change. Thus, problems (melting, pesky ice crystals) will only happen if it's exposed to extreme temperatures for a prolonged period. By measuring this data, the ice cream manufacturer can impose quality controls on each batch of product they’re storing in the freezer.</p>
<p>Taking this into account, the sensors in the freezer measure temperature in the following way: when the door is closed and we’re in the optimal range, the sensors take a measurement every 5 minutes; when the door is opened, the sensors take a measurement every 30 seconds until the door is closed, and the temperature has returned below 10℉.</p>
<p>To model that we might have a simple table like this:</p>
<pre><code class="language-SQL">CREATE TABLE freezer_temps (
	freezer_id int,
	ts timestamptz,
	temperature float);
</code></pre>
<p>And some data like this:</p>
<pre><code class="language-SQL">INSERT INTO freezer_temps VALUES 
( 1, '2020-01-01 00:00:00+00', 4.0), 
( 1, '2020-01-01 00:05:00+00', 5.5), 
( 1, '2020-01-01 00:10:00+00', 3.0), 
( 1, '2020-01-01 00:15:00+00', 4.0), 
( 1, '2020-01-01 00:20:00+00', 3.5), 
( 1, '2020-01-01 00:25:00+00', 8.0), 
( 1, '2020-01-01 00:30:00+00', 9.0), 
( 1, '2020-01-01 00:31:00+00', 10.5), -- door opened!
( 1, '2020-01-01 00:31:30+00', 11.0), 
( 1, '2020-01-01 00:32:00+00', 15.0), 
( 1, '2020-01-01 00:32:30+00', 20.0), -- door closed
( 1, '2020-01-01 00:33:00+00', 18.5), 
( 1, '2020-01-01 00:33:30+00', 17.0), 
( 1, '2020-01-01 00:34:00+00', 15.5), 
( 1, '2020-01-01 00:34:30+00', 14.0), 
( 1, '2020-01-01 00:35:00+00', 12.5), 
( 1, '2020-01-01 00:35:30+00', 11.0), 
( 1, '2020-01-01 00:36:00+00', 10.0), -- temperature stabilized
( 1, '2020-01-01 00:40:00+00', 7.0),
( 1, '2020-01-01 00:45:00+00', 5.0);
</code></pre>
<p>The period after the door opens, minutes 31-36, has a lot more data points. If we were to take the average of all the points, we would get a misleading value. The freezer was only above the threshold temperature for 5 out of 45 minutes (11% of the time period), but those minutes make up 10 out of 20 data points (50%!) because we sample freezer temperature more frequently after the door is opened.</p>
<p>To find the more accurate, time-weighted average temperature, let’s write the SQL for the formula above that handles that case. We’ll also get the normal average just for comparison’s sake. (Don’t worry if you have trouble reading it, we’ll write a much simpler version later).</p>
<pre><code class="language-SQL">WITH setup AS (
	SELECT lag(temperature) OVER (PARTITION BY freezer_id ORDER BY ts) as prev_temp, 
		extract('epoch' FROM ts) as ts_e, 
		extract('epoch' FROM lag(ts) OVER (PARTITION BY freezer_id ORDER BY ts)) as prev_ts_e, 
		* 
	FROM  freezer_temps), 
nextstep AS (
	SELECT CASE WHEN prev_temp is NULL THEN NULL 
		ELSE (prev_temp + temperature) / 2 * (ts_e - prev_ts_e) END as weighted_sum, 
		* 
	FROM setup)
SELECT freezer_id,
    avg(temperature), -- the regular average
	sum(weighted_sum) / (max(ts_e) - min(ts_e)) as time_weighted_average -- our derived average
FROM nextstep
GROUP BY freezer_id;
</code></pre>
<pre><code class="language-SQL"> freezer_id |  avg  | time_weighted_average 
------------+-------+-----------------------
          1 | 10.2  |     6.636111111111111
</code></pre>
<p>It does return what we want, and gives us a much better picture of what happened, but it’s not exactly fun to write, is it?</p>
<p>We’ve got a few window functions in there, some case statements to deal with nulls, and several CTEs to try to make it reasonably clear what’s going on. <strong>This is the kind of thing that can really lead to code maintenance issues when people try to figure out what’s going on and tweak it.</strong></p>
<p>Code is all about managing complexity. A long, complex query to accomplish a relatively simple task makes it much less likely that the developer who comes along next (ie you in 3 months) will understand what’s going on, how to use it, or how to change it if they (or you!) need a different result.  Or, worse, it means that the code will never get changed because people don’t quite understand what the query’s doing, and it just becomes a black box that no one wants to touch (including you).</p>
<h2 id="timescaledb-hyperfunctions-to-the-rescue">TimescaleDB hyperfunctions to the rescue!</h2>
<p>This is why we created <strong><a href="https://docs.timescale.com/api/latest/hyperfunctions/">hyperfunctions</a></strong>, to make complicated time-series data analysis less complex. Let’s look at what the time-weighted average freezer temperature query looks like if we use the <a href="https://docs.timescale.com/api/latest/hyperfunctions/time-weighted-averages/">hyperfunctions for computing time-weighted averages</a>:</p>
<pre><code class="language-SQL">SELECT freezer_id, 
	avg(temperature), 
	average(time_weight('Linear', ts, temperature)) as time_weighted_average 
FROM freezer_temps
GROUP BY freezer_id;
</code></pre>
<pre><code class="language-SQL"> freezer_id |  avg  | time_weighted_average 
------------+-------+-----------------------
          1 | 10.2  |     6.636111111111111
</code></pre>
<p>Isn’t that so much more concise?! Calculate a <a href="https://docs.timescale.com/api/latest/hyperfunctions/time-weighted-averages/time_weight/"><code>time_weight</code></a> with a <code>'Linear'</code> weighting method (that’s the kind of weighting derived above <sup class="footnote-ref"><a href="#fn2" id="fnref2">[2]</a></sup>), then take the average of the weighted values, and we’re done. I like that API much better (and I’d better, because I designed it!).</p>
<p>What’s more, not only do we save ourselves from writing all that SQL, but it also becomes far, far easier to <strong>compose</strong> (build up more complex analyses over top of the time-weighted average). This is a huge part of the design philosophy behind hyperfunctions; we want to make fundamental things simple so that you can easily use them to build more complex, application-specific analyses.</p>
<p>Let’s imagine we’re not satisfied with the average over our entire dataset, and we want to get the time-weighted average for every 10-minute bucket:</p>
<pre><code class="language-SQL">SELECT time_bucket('10 mins'::interval, ts) as bucket, 
	freezer_id, 
	avg(temperature), 
	average(time_weight('Linear', ts, temperature)) as time_weighted_average 
FROM freezer_temps
GROUP BY bucket, freezer_id;
</code></pre>
<p>We added a <a href="https://docs.timescale.com/api/latest/hyperfunctions/time_bucket/"><code>time_bucket</code></a>, grouped by it, and done! Let’s look at some other kinds of sophisticated analysis that hyperfunctions enable.</p>
<p>Continuing with our ice cream example, let’s say that we’ve set our threshold because we know that if the ice cream spends more than 15 minutes above 15 ℉, it’ll develop those ice crystals that make it all sandy/grainy tasting. We can use the time-weighted average in a <a href="https://www.postgresql.org/docs/current/functions-window.html">window function</a> to see if that happened:</p>
<pre><code class="language-SQL">SELECT *, 
    average(time_weight('Linear', ts, temperature) OVER fifteen_min) as rolling_twa
FROM freezer_temps
WINDOW fifteen_min AS 
    (PARTITION BY freezer_id ORDER BY ts RANGE  '15 minutes'::interval PRECEDING)
ORDER BY freezer_id, ts;
</code></pre>
<pre><code class="language-SQL">
 freezer_id |           ts           | temperature |    rolling_twa     
------------+------------------------+-------------+--------------------
          1 | 2020-01-01 00:00:00+00 |           4 |                   
          1 | 2020-01-01 00:05:00+00 |         5.5 |               4.75
          1 | 2020-01-01 00:10:00+00 |           3 |                4.5
          1 | 2020-01-01 00:15:00+00 |           4 |  4.166666666666667
          1 | 2020-01-01 00:20:00+00 |         3.5 | 3.8333333333333335
          1 | 2020-01-01 00:25:00+00 |           8 |  4.333333333333333
          1 | 2020-01-01 00:30:00+00 |           9 |                  6
          1 | 2020-01-01 00:31:00+00 |        10.5 |  7.363636363636363
          1 | 2020-01-01 00:31:30+00 |          11 |  7.510869565217392
          1 | 2020-01-01 00:32:00+00 |          15 |  7.739583333333333
          1 | 2020-01-01 00:32:30+00 |          20 |               8.13
          1 | 2020-01-01 00:33:00+00 |        18.5 |  8.557692307692308
          1 | 2020-01-01 00:33:30+00 |          17 |  8.898148148148149
          1 | 2020-01-01 00:34:00+00 |        15.5 |  9.160714285714286
          1 | 2020-01-01 00:34:30+00 |          14 |   9.35344827586207
          1 | 2020-01-01 00:35:00+00 |        12.5 |  9.483333333333333
          1 | 2020-01-01 00:35:30+00 |          11 | 11.369047619047619
          1 | 2020-01-01 00:36:00+00 |          10 | 11.329545454545455
          1 | 2020-01-01 00:40:00+00 |           7 |             10.575
          1 | 2020-01-01 00:45:00+00 |           5 |  9.741666666666667
</code></pre>
<p>The window here is over the previous 15 minutes, ordered by time. And it looks like we stayed below our ice-crystallization temperature!</p>
<p>We also provide a special <a href="https://docs.timescale.com/api/latest/hyperfunctions/time-weighted-averages/rollup-timeweight/"><code>rollup</code></a> function so you can re-aggregate time-weighted values from subqueries. For instance:</p>
<pre><code class="language-SQL">SELECT average(rollup(time_weight)) as time_weighted_average 
FROM (SELECT time_bucket('10 mins'::interval, ts) as bucket, 
		freezer_id, 
		time_weight('Linear', ts, temperature)
	FROM freezer_temps
	GROUP BY bucket, freezer_id) t;
</code></pre>
<pre><code class="language-SQL">time_weighted_average 
-----------------------
    6.636111111111111
</code></pre>
<p>This will give us the same output as a grand total of the first equation because we’re just re-aggregating the bucketed values.</p>
<p>But this is mainly there so that you can do more interesting analysis, like, say, normalizing each ten-minute time-weighted average by freezer to the overall time-weighted average.</p>
<pre><code class="language-SQL">WITH t as (SELECT time_bucket('10 mins'::interval, ts) as bucket, 
		freezer_id, 
		time_weight('Linear', ts, temperature)
	FROM freezer_temps
	GROUP BY bucket, freezer_id) 
SELECT bucket, 
	freezer_id, 
	average(time_weight) as bucketed_twa,  
	(SELECT average(rollup(time_weight)) FROM t) as overall_twa, 
	average(time_weight) / (SELECT average(rollup(time_weight)) FROM t) as normalized_twa
FROM t; 
</code></pre>
<p>This kind of feature (storing the time-weight for analysis later) is most useful in a <a href="https://docs.timescale.com/timescaledb/latest/how-to-guides/continuous-aggregates/">continuous aggregate</a>, and it just so happens that we’ve designed our time-weighted average to be usable in that context!</p>
<p>We’ll be going into more detail on that in a future post, so be sure to <a href="https://www.timescale.com/signup/newsletter">subscribe to our newsletter</a> so you can get notified when we publish new technical content.</p>
<h2 id="try-time-weighted-averages-today">Try time-weighted averages today</h2>
<p><strong>If you’d like to get started with the time_weight hyperfunction - and many more - right away, spin up a fully managed TimescaleDB service:</strong> create an account to <a href="http://console.cloud.timescale.com/signup">try it for free</a> for 30 days. Hyperfunctions are pre-loaded on each new database service on Timescale, so after you create a new service, you’re all set to use them!</p>
<p><strong>If you prefer to manage your own database instances, you can <a href="https://github.com/timescale/timescaledb-toolkit">download and install the timescaledb_toolkit extension</a></strong> on GitHub, after which you’ll be able to use time_weight and all other hyperfunctions.</p>
<p>**If you have questions or comments on this blog post, <a href="https://github.com/timescale/timescaledb-toolkit/discussions/185">we’ve started a discussion on our GitHub page, and we’d love to hear from you</a>. (And, if you like what you see, GitHub ⭐ are always welcome and appreciated too!)</p>
<ul>
<li>We love building in public, and you can view our <a href="https://github.com/timescale/timescaledb-toolkit">upcoming roadmap on GitHub</a> for a list of proposed features, features we’re currently implementing, and features available to use today.</li>
</ul>
<p>We’d like to give a special thanks to <a href="https://github.com/inselbuch">@inselbuch</a>, who <a href="https://github.com/timescale/timescaledb-toolkit/issues/46">submitted the GitHub issue</a> that got us started on this project (as well as the other folks who 👍’d it and let us know they wanted to use it.)</p>
<p>We believe time-series data is everywhere, and making sense of it is crucial for all manner of technical problems. We built hyperfunctions to make it easier for developers to harness the power of time-series data. We’re always looking for feedback on what to build next and would love to know how you’re using hyperfunctions, problems you want to solve, or things you think should - or could - be simplified to make analyzing time-series data in SQL that much better. (To contribute feedback, comment on an <a href="https://github.com/timescale/timescaledb-toolkit/issues">open issue</a> or in a <a href="https://github.com/timescale/timescaledb-toolkit/discussions">discussion thread</a> in GitHub.)</p>
<p>Lastly, in future posts, we’ll give some more context around our design philosophy, decisions we’ve made around our APIs for time-weighted averages (and other features), and detailing how other hyperfunctions work. So, if that’s your bag, you’re in luck – but you’ll have to wait a week or two.</p>
<hr class="footnotes-sep">
<section class="footnotes">
<ol class="footnotes-list">
<li id="fn1" class="footnote-item"><p>I don’t know that these times or temperatures are accurate per se; however, the phenomenon of ice cream partially melting and refreezing causing larger ice crystals to form - and coarsening the ice cream as a result - is well documented. See, for instance, <a href="https://peoplegetreadybooks.com/?q=h.tviewer&amp;using_sb=status&amp;qsb=keyword&amp;qse=OqerFF92q0vIs_NOprdwmw">Harold McGee’s On Food And Cooking</a> (p 44 in the 2004 revised edition). So, just in case you are looking for advice on storing your ice cream from a blog about time-series databases: for longer-term storage, you would likely want the ice cream to be stored below 0℉. Our example is more like a scenario you’d see in an ice cream display (e.g., in an ice cream parlor or factory line) since the ice cream is kept between 0-10℉ (ideal for scooping, because lower temperatures make ice cream too hard to scoop). <a href="#fnref1" class="footnote-backref">↩︎</a></p>
</li>
<li id="fn2" class="footnote-item"><p>We also offer <code>’LOCF’</code> or last observation carried forward weighting, which is best suited to cases where you record data points whenever the value changes (i.e., the old value is valid until you get a new one.)</p>
<p>The derivation for that is similar, except the rectangles have the height of the first value, rather than the linear weighting we’ve discussed in this post (i.e., where we do linear interpolation between adjacent data points):</p>
<p><img src="https://timescale.ghost.io/blog/content/images/2021/07/LOCF-Weighting.png" alt="LOCF-Weighting" loading="lazy"><br>
Rather than:<br>
<img src="https://timescale.ghost.io/blog/content/images/2021/07/Linear-Weighting.png" alt="Linear-Weighting" loading="lazy"></p>
<p>In general, linear weighting is appropriate for cases where the sampling rate is variable, but there are no guarantees provided by the system about only providing data when it changes. LOCF works best when there’s some guarantee that your system will provide data only when it changes, and you can accurately carry the old value until you receive a new one. <a href="#fnref2" class="footnote-backref">↩︎</a></p>
</li>
</ol>
</section>
]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Hyperfunctions: New SQL Functions to Simplify Working With Time-Series Data in PostgreSQL]]></title>
            <description><![CDATA[TimescaleDB hyperfunctions are pre-built functions for the most common and difficult queries that developers write today in TimescaleDB and PostgreSQL. Hyperfunctions help developers measure what matters in time-series data, which generates massive, ever-growing streams of information.]]></description>
            <link>https://www.tigerdata.com/blog/introducing-hyperfunctions-new-sql-functions-to-simplify-working-with-time-series-data-in-postgresql</link>
            <guid isPermaLink="true">https://www.tigerdata.com/blog/introducing-hyperfunctions-new-sql-functions-to-simplify-working-with-time-series-data-in-postgresql</guid>
            <category><![CDATA[Announcements & Releases]]></category>
            <category><![CDATA[Engineering]]></category>
            <category><![CDATA[PostgreSQL]]></category>
            <dc:creator><![CDATA[Joshua Lockerman]]></dc:creator>
            <pubDate>Tue, 13 Jul 2021 13:02:11 GMT</pubDate>
            <media:content medium="image" href="https://timescale.ghost.io/blog/content/images/2021/07/ryan-stone-OlxJVn9fxz4-unsplash.jpg">
            </media:content>
            <content:encoded><![CDATA[<p></p><p>Today, we’re excited to launch <strong>TimescaleDB hyperfunctions</strong>, a series of SQL functions within TimescaleDB that make it easier to manipulate and analyze time-series data in PostgreSQL with fewer lines of code. You can use hyperfunctions to calculate percentile approximations of data, compute time-weighted averages, downsample and smooth data, and perform faster <code>COUNT DISTINCT</code> queries using approximations. Moreover, hyperfunctions are “easy” to use: you call a hyperfunction using the same SQL syntax you know and love.</p>
<p>At Timescale, our mission is to <a href="https://www.timescale.com/products" rel="noreferrer">enable every software developer to store, analyze, and build on top of their time-series data</a> so that they can measure what matters in their world: IoT devices, IT systems, marketing analytics, user behavior, financial metrics, and more.</p><p>We made the decision early in the design of TimescaleDB to build on top of PostgreSQL. We believed then, as we do now, that building on the <a href="https://db-engines.com/en/blog_post/85">world’s fastest-growing database</a> would have numerous benefits for our customers. Perhaps the biggest of these advantages is in developer productivity. Developers can use the tools and frameworks they know and love and bring all their skills and expertise with SQL with them.</p><p>SQL is a powerful language and we believe that by adding a specialized set of functions for time-series analysis, we can make it even better.</p><p>Today, there are nearly three million active TimescaleDB databases running mission-critical time-series workloads across industries. Time-series data comes at you fast, sometimes generating millions of data points per second. In order to measure everything that matters, you need to capture all of the data you possibly can. Because of the volume and rate of information, time-series data can be complex to query and analyze. </p><p>As we interviewed customers and learned how they analyze and manipulate time-series data, we noticed several common queries begin to take shape. Often, these queries were difficult to compose in standard SQL. TimescaleDB hyperfunctions are a series of SQL functions to address the most common, and often most difficult, queries developers write today. We made the decision to take the hard path ourselves so that we could give developers an easier path.</p><h3 id="hyperfunctions-included-in-this-initial-release">Hyperfunctions included in this initial release</h3><p>Today, we’re releasing several hyperfunctions, including:</p><ul>
<li><strong>Time-Weighted Average</strong> allows you to take the average over an irregularly spaced dataset that only includes changepoints.</li>
<li><strong>Percentile-Approximation</strong> brings percentile analysis to more workflows. When used with <a href="https://timescale.ghost.io/blog/blog/continuous-aggregates-faster-queries-with-automatically-maintained-materialized-views/">continuous aggregates</a>, you can compute percentiles over any time range of your dataset in near real-time and use them for baselining and normalizing incoming data. For maximum control, we provide implementations of two different approximation algorithms:
<ul>
<li><strong>Uddsketch</strong> gives formal guarantees to the accuracy of approximate percentiles, in exchange for always returning a range of possible values.</li>
<li><strong>T-Digest</strong> gives fuzzier guarantees which allow it to be more precise at the extremes of the distribution.</li>
</ul>
</li>
<li><strong>Hyperloglog</strong> enables faster approximate <code>COUNT DISTINCT</code>, making it easier to track how the cardinality of your data changes over time.</li>
<li><strong>Counter Aggregate</strong> enables working with counters in an ergonomic SQL-native manner.</li>
<li><strong>ASAP Smoothing</strong> smooths datasets to bring out the most important features when graphed.</li>
<li><strong>Largest Triangle Three Buckets Downsampling</strong> reduces the number of elements in a dataset while retaining important features when graphed.</li>
<li><strong>Stats-agg</strong> makes using rolling, cumulative and normalized statistics as easy as their standard counterparts.</li>
</ul>
<p>Note that Hyperfunctions work on TimescaleDB <a href="https://docs.timescale.com/api/latest/hypertable/">hypertables</a>, as well as regular PostgreSQL tables.</p><h3 id="new-sql-functions-not-new-sql-syntax">New SQL functions, not new SQL syntax</h3><p>We made the decision to create <strong>new SQL functions</strong> for each of the time-series analysis and manipulation capabilities above. This stands in contrast to other efforts which aim to improve the developer experience by introducing new SQL <em>syntax</em>. </p><p>While introducing new syntax with new keywords and new constructs may have been easier from an implementation perspective, we made the deliberate decision not to do so since we believe that it actually leads to a worse experience for the end-user. </p><p>New SQL syntax means that existing drivers, libraries, and tools may no longer work. This can leave developers with more problems than solutions as their favorite tools, libraries, or drivers may not support the new syntax, or may require time-consuming modifications to do so. </p><p>On the other hand, new SQL functions mean that your query will run in every visualization tool, database admin tool, or data analysis tool. We have the freedom to create custom functions, aggregates, and procedures that help developers better understand and work with their data, <strong>and </strong>ensure all their drivers and interfaces still work as expected.</p><h3 id="hyperfunctions-are-written-in-rust">Hyperfunctions are written in Rust</h3><p>Rust was our language of choice for developing the new hyperfunctions. We chose it for its superior productivity, community, and the <a href="https://github.com/zombodb/pgx">pgx software development kit</a>. We felt Rust was a more friendly language for a project like ours and would encourage more community contributions. </p><p>The inherent safety of Rust means we could focus more time on feature development rather than worrying about how the code is written. The extensive Rust community (💗 <a href="http://crates.io">crates.io</a>), along with excellent package-management tools, means we can use off-the-shelf solutions for common problems, leaving us more time to focus on the uncommon ones. </p><p>On the topic of community, we found the Rust community to be one of the friendliest on the internet, and its commitment to open source, open communication, and good documentation make it an utter joy to work with. Libraries such as <a href="https://serde.rs/">Serde</a> and <a href="https://github.com/BurntSushi/quickcheck">quickcheck </a>make common tasks a breeze and lets us focus on the code that’s novel to our project, instead of writing boilerplate that's already been written by thousands of others. </p><p>We’d like to shout out ZomboDB’s <a href="https://github.com/zombodb/pgx">pgx</a>, an SDK for building <a href="https://www.tigerdata.com/blog/top-8-postgresql-extensions" rel="noreferrer">Postgres extensions</a> using Rust. Pgx provides tools to generate extension scripts from Rust files and bind Rust functions to Postgres functions, as well as tools to set up, run, and test PostgreSQL instances. (For us, it’s been an amazing tool and experience with incredible benefits – we estimate that pgx has reduced our workload by at least one-third!.)</p><h3 id="next-steps">Next steps</h3><p>In the rest of this post, we detail why we chose to build new SQL functions (not new SQL syntax), and explore each hyperfunction and its example usage.</p><p>But<strong> if you’d like to get started with hyperfunctions right away, the easiest way to do so is with a fully-managed TimescaleDB service</strong>. <a href="https://console.cloud.timescale.com/signup">Try it for free</a> (no credit card required) for 30 days. Hyperfunctions are pre-loaded on each new database service on Timescale, so after you’ve created a new service, you’re all set to use them!</p><p><strong>If you prefer to manage your own database instances, you can </strong><a href="https://github.com/timescale/timescaledb-toolkit"><strong>download and install the timescaledb_toolkit extension</strong></a> on GitHub for free, after which you’ll be able to use all the hyperfunctions listed above. </p><p>Finally, we love building in public. You can view our <a href="https://github.com/timescale/timescaledb-toolkit">upcoming roadmap on GitHub</a> for a list of proposed features, as well as features we’re currently implementing and those that are available to use today. </p><p>We also welcome feedback from the community (it helps us prioritize the features users really want). To contribute feedback, comment on an <a href="https://github.com/timescale/timescaledb-toolkit/issues">open issue</a> or in a <a href="https://github.com/timescale/timescaledb-toolkit/discussions">discussion thread</a> in GitHub.</p><p>To learn more about hyperfunctions, please continue reading.</p><h2 id="building-new-sql-functions-instead-of-reinventing-syntax">Building new SQL functions instead of reinventing syntax</h2><p>SQL is the <a href="https://insights.stackoverflow.com/survey/2020#most-popular-technologies">third most popular programming language in the world</a>. It’s the language known and loved by many software developers, data scientists, and business analysts the world over, and it's a big reason we chose to build TimescaleDB on top of PostgreSQL in the first place.</p><p>Similarly, we choose to make our APIs user-friendly without breaking full SQL compatibility. This means we can create custom functions, aggregates, and procedures but no new syntax - and all the drivers and interfaces can still work. You get the peace of mind that your query will run in every visualization tool, database admin tool, or data analysis tool that speaks SQL.</p><p>SQL is powerful and it’s even <a href="http://blog.coelho.net/database/2013/08/17/turing-sql-1.html">Turing complete</a>, so you can technically do anything with it. But that doesn’t mean you’d want to 😉. Our hyperfunctions are made to make complex analysis and time-series manipulation in SQL simpler, without undermining the guarantees of full SQL compatibility. We’ve spent a large amount of our time on design; prototyping and just writing out different names and calling conventions for clarity and ease of use. </p><p>Our guiding philosophy is to make simple things easy and complex things possible. We enable things that <em>feel</em> like they should be straightforward, like using a single function call to calculate a time-weighted average of a single item over a time period. We also enable operations that would otherwise be prohibitively expensive (in terms of complexity to write) or would previously take too long to respond to be useful. For example, calculating a rolling time-weighted average of each item normalized to the monthly average of the whole group of things.</p><p>For example, we’ve implemented a default for percentile approximation called <code>percentile_agg</code>  that should work for most users, while also exposing the lower level <code>UDDsketch</code> and <code>tdigest</code> implementations for users who want to have more control and get into the weeds.</p>
<p>Another advantage of using SQL functions rather than new syntax is that we bring your code closer to your data, rather than forcing you to take your data to your code. Simply put, you can now perform more sophisticated analysis and manipulation operations on your data right inside your database, rather than creating data pipelines to funnel data into Python or other analysis libraries to conduct analysis there. </p><p>We want to make the more complex analysis simpler and easier in the database not just because we want to build a good product, but also because it’s far, far more efficient to do your analysis as close to the data as possible, and then get aggregated or other simpler results that get passed back to the user. </p><p>This is because the network transmission step is often the slowest and most expensive part of many calculations, and because the serialization and deserialization overhead can be very large as you get to large datasets. So by making these functions and all sorts of analysis simpler to perform in the database, nearer to the data, developers save time and money.</p><p>Moreover, while you could perform some of the complex analysis enabled by hyperfunctions in other languages inside the database (e.g., programs in Python or R), hyperfunctions now enable you to perform such sophisticated time-series analysis and manipulation in SQL right in your query statements, making them more accessible.</p><h2 id="hyperfunctions-released-today">Hyperfunctions released today</h2><p>Hyperfunctions refactor some of the most gnarly SQL queries for time-series data into concise, elegant functions that feel natural to any developer that knows SQL. Let’s walk through the hyperfunctions we’re releasing today and the ones that will be available soon.</p><p>Back in January, <a href="https://timescale.ghost.io/blog/blog/time-series-analytics-for-postgresql-introducing-the-timescale-analytics-project/">when we launched our initial hyperfunctions release</a>, we asked for feedback and input from the community. We want this to be a community-driven project, so for our 1.0 release, we’ve prioritized several features requested by community members. We’ll have a brief overview here, with a technical deep dive into each family of functions in a series of separate blog posts in the coming weeks.</p><p><strong>Time-weighted averages</strong></p><p>Time-series averages can be complicated to calculate; generally, you need to determine how long each value has been recorded in order to know how much to weigh them. While doing this in native SQL is <em>possible</em>, it is extremely error-prone and unwieldy. More damningly, the SQL needed would not work in every context. In particular, it would not work in TimescaleDB’s automatically refreshing materialized views, <a href="https://timescale.ghost.io/blog/blog/continuous-aggregates-faster-queries-with-automatically-maintained-materialized-views/">continuous aggregates</a>, so users who wanted to calculate time-weighted averages over multiple time intervals would be forced to rescan the entire dataset for each average so calculated. Our time-weighted average hyperfunction removes this complexity and can be used in continuous aggregates to make multi-interval time-weighted averages as cheap as summing a few sub-averages.</p><p>Here’s an example of using time-weighted averages for an IoT use case, specifically to find the average temperature in a set of freezers over time. (Notice how it takes sixteen lines of complex code to find the time-weighted average using regular SQL, compared just five lines of code with <code>SELECT</code> statements when using the TimescaleDB hyperfunction):</p>
<p><strong>Time-weighted average using TimescaleDB hyperfunction</strong></p><pre><code class="language-SQL">SELECT freezer_id, 
	avg(temperature), 
	average(time_weight('Linear', ts, temperature)) as time_weighted_average 
FROM freezer_temps
GROUP BY freezer_id;
</code></pre>
<pre><code class="language-output"> freezer_id |  avg  | time_weighted_average 
------------+-------+-----------------------
          1 | 10.35 |     6.802777777777778
</code></pre>
<p><strong>Time-weighted average using regular SQL</strong></p><pre><code class="language-SQL">WITH setup AS (
	SELECT lag(temperature) OVER (PARTITION BY freezer_id ORDER BY ts) as prev_temp, 
		extract('epoch' FROM ts) as ts_e, 
		extract('epoch' FROM lag(ts) OVER (PARTITION BY freezer_id ORDER BY ts)) as prev_ts_e, 
		* 
	FROM  freezer_temps), 
nextstep AS (
	SELECT CASE WHEN prev_temp is NULL THEN NULL 
		ELSE (prev_temp + temperature) / 2 * (ts_e - prev_ts_e) END as weighted_sum, 
		* 
	FROM setup)
SELECT freezer_id, 
	avg(temperature),
	sum(weighted_sum) / (max(ts_e) - min(ts_e)) as time_weighted_average 
FROM nextstep
GROUP BY freezer_id;
</code></pre>
<pre><code class="language-output"> freezer_id |  avg  | time_weighted_average 
------------+-------+-----------------------
          1 | 10.35 |     6.802777777777778
</code></pre>
<p><strong>Percentile approximation (UDDsketch &amp; TDigest)</strong></p><p>Aggregate statistics are useful when you know the underlying distribution of your data, but for other cases, they <a href="https://en.wikipedia.org/wiki/Anscombe%27s_quartet">can be misleading</a>. For cases where they don’t work, and for more exploratory analyses looking at the ground truth, <a href="https://en.wikipedia.org/wiki/Percentile">percentiles</a> are useful. </p><p>As useful as it is, percentile analysis comes with one major downside: it needs to store the entire dataset in memory. This means that such analysis is only feasible for relatively small datasets, and even then can take longer than ideal to calculate. </p><p>The approximate-percentile hyperfunctions we’ve implemented suffer from neither of these problems: they take constant storage, and, when combined with automatically refreshing materialized views, they can produce results nearly instantaneously. This performance improvement opens up opportunities to use percentile analysis for use cases and datasets where it was previously unfeasible.</p><p>Here’s an example of using percentile approximation for a DevOps use case, where we alert on response times that are over the 95th percentile:</p><pre><code class="language-SQL">WITH “95th percentile” as (
    SELECT approx_percentile(0.95, percentile_agg(response_time)) as threshold
    FROM response_times
)
SELECT count(*) 
FROM response_times 
AND response_time &gt; “95th percentile”.threshold;
</code></pre>
<p><a href="https://docs.timescale.com/api/latest/hyperfunctions/">See our hyperfunctions docs</a> to get started today. In the coming weeks, we will be releasing a series of blog posts which detail each of the hyperfunctions released today, in the context of using them to solve a real-world problem. </p><h3 id="hyperfunctions-in-public-preview">Hyperfunctions in public preview</h3><p>In addition to the hyperfunctions released today, we’re making several hyperfunctions available for public preview. These include hyperfunctions for downsampling, smoothing, approximate count-distinct, working with counters, and working with more advanced forms of averaging. All of these are available for trial today through our experimental schema, and, with your feedback, will be made available for production usage soon. </p><p>Here’s a tour through each hyperfunction and why we created them:</p><p><strong>Graph Downsampling &amp; Smoothing</strong></p><p>We have two algorithms implemented to help downsample your data for better, faster graphing:</p><p>The first graphing algorithm for downsampling is <a href="https://github.com/timescale/timescaledb-toolkit/blob/main/docs/lttb.md"><strong>Largest triangle three bucket</strong></a><strong> (LTTB)</strong>. LTTB limits the number of points you need to send to your graphing engine while maintaining visual acuity. This means that you don’t try to plot 200,000 points on a graph that’s only 2000 pixels wide, which is inefficient in terms of network and rendering costs. </p><p>Given an original dataset which looks like the graph below:</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/01/lttb_raw.png" class="kg-image" alt="" loading="lazy" width="716" height="371" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/lttb_raw.png 600w, https://timescale.ghost.io/blog/content/images/2022/01/lttb_raw.png 716w"></figure><p>We can downsample it to just 34 points with the following query using the LTTB hyperfunction:</p><pre><code>SELECT toolkit_experimental.lttb(time, val, 34)
</code></pre>
<p>The above query yields the following graph, which retains the periodic pattern of the original graph, with just 34 points of data.</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/01/lttb_34.png" class="kg-image" alt="" loading="lazy" width="600" height="371" srcset="https://timescale.ghost.io/blog/content/images/2022/01/lttb_34.png 600w"></figure><p>The second graphing algorithm for downsampling is <a href="https://github.com/timescale/timescaledb-toolkit/blob/main/docs/asap.md"><strong>Automatic smoothing for attention prioritization</strong></a><strong> (ASAP smoothing). </strong>ASAP Smoothing uses optimal moving averages to smooth a graph to remove noise and make sure that trends are obvious to the user, while not over-smoothing and removing all the signals as well. This leads to vastly improved readability. </p><p>For example, the graph below displays 250 years of monthly temperature readings from England (raw data can be found <a href="http://futuredata.stanford.edu/asap/Temp.csv">here</a>):</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/01/ASAP_raw.png" class="kg-image" alt="" loading="lazy" width="809" height="341" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/ASAP_raw.png 600w, https://timescale.ghost.io/blog/content/images/2022/01/ASAP_raw.png 809w" sizes="(min-width: 720px) 720px"></figure><p>We can run the following query using the ASAP smoothing hyperfunction:</p><pre><code>SELECT toolkit_experimental.asap_smooth(month, value, 800) FROM temperatures
</code></pre>
<p>The result is the graph below, which is much less noisy than the original and one where users can more easily spot trends.</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/01/ASAP_smoothed.png" class="kg-image" alt="Smoothed data" loading="lazy" width="809" height="341" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/ASAP_smoothed.png 600w, https://timescale.ghost.io/blog/content/images/2022/01/ASAP_smoothed.png 809w" sizes="(min-width: 720px) 720px"></figure><p><a href="https://github.com/timescale/timescaledb-toolkit/blob/main/docs/counter_agg.md"><strong>Counter Aggregates</strong></a></p><p>Metrics generally come in a few different varieties, which many systems have come to call <strong>gauges</strong> and <strong>counters</strong>. A gauge is a typical metric that can vary up or down, something like temperature or percent utilization. A counter is meant to be monotonically increasing. So it keeps track of, say, the total number of visitors to a website. The main difference in processing counters and gauges is that a decrease in the value of a counter (compared to its previous value in the <a href="https://www.tigerdata.com/blog/time-series-introduction" rel="noreferrer">time series</a>) is interpreted as a <strong>reset</strong>.  TimescaleDB’s <a href="https://github.com/timescale/timescaledb-toolkit/blob/main/docs/counter_agg.md">counter aggregate hyperfunctions</a> enable a simple and optimized analysis of these counters. </p><p>For example, despite a dataset being stored like:</p><pre><code>data
------
  10
  20
   0
   5
  15
</code></pre>
<p>We can calculate the delta (along with various other statistics) over this monotonically-increasing counter with the following query using the counter aggregate hyperfunction:</p><pre><code>SELECT toolkit_experimental.delta(
    toolkit_experimental.counter_agg(ts, val))
FROM foo;
</code></pre>
<pre><code> delta
------
  40
</code></pre>
<p><a href="https://github.com/timescale/timescaledb-toolkit/blob/main/docs/hyperloglog.md"><strong>Hyperloglog for Approximate Count Distinct</strong></a></p><p>We’ve implemented a version of the hyperloglog algorithm to do approximate count distinct queries over data in a more efficient and parallelizable fashion. For existing TimescaleDB users, you’d be happy to hear that they work in continuous aggregates, which are automatically refreshing materialized views. </p><p><a href="https://github.com/timescale/timescaledb-toolkit/blob/main/docs/stats_agg.md"><strong>Statistical Aggregates</strong></a></p><p>Calculating rolling averages and other statistical aggregates over tumbling windows is very difficult in standard SQL because to do it accurately you’d need to separate out the different components (i.e., for average, count and sum) and then calculate it yourself. Our statistical aggregates allow you to simply do this, with simple <code>rollup</code>.</p>
<p>To follow the progress and contribute to improving these (and future) hyperfunctions, you can view our <a href="https://github.com/timescale/timescaledb-toolkit">roadmap on GitHub.</a> Our development process is heavily influenced by community feedback, so your comments on <a href="https://github.com/timescale/timescaledb-toolkit/issues">issues</a> and <a href="https://github.com/timescale/timescaledb-toolkit/discussions">discussion threads</a> will help determine which features get prioritized, and when they’re stabilized for release.</p><h2 id="next-steps-1">Next Steps</h2><p><a href="https://console.cloud.timescale.com/signup">Try hyperfunctions today</a> with a fully-managed Timescale service (no credit card required, free for 30 days). Hyperfunctions are pre-loaded on each new database service on Timescale, so after you’ve created a new service, you’re all set to use them!</p><p>If you prefer to manage your own database instances, you can <a href="https://github.com/timescale/timescaledb-toolkit">download and install the timescaledb_toolkit extension</a> on GitHub for free, after which you’ll be able to use all the hyperfunctions listed above. </p><p>We love building in public. You can view our <a href="https://github.com/timescale/timescaledb-toolkit">upcoming roadmap on GitHub</a> for a list of proposed features, as well as features we’re currently implementing and those that are available to use today. We also welcome feedback from the community (it helps us prioritize the features users really want). To contribute feedback, comment on an <a href="https://github.com/timescale/timescaledb-toolkit/issues">open issue</a> or in a <a href="https://github.com/timescale/timescaledb-toolkit/discussions">discussion thread</a> in GitHub.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time-Series Analytics for PostgreSQL: Introducing the Timescale Analytics Project]]></title>
            <description><![CDATA[We're excited to announce Timescale Analytics, a new project focused on combining all of the capabilities SQL needs to perform time-series analytics into one Postgres extension. Learn about our plans, why we're sharing it now, and ways to contribute your feedback and ideas.  ]]></description>
            <link>https://www.tigerdata.com/blog/time-series-analytics-for-postgresql-introducing-the-timescale-analytics-project</link>
            <guid isPermaLink="true">https://www.tigerdata.com/blog/time-series-analytics-for-postgresql-introducing-the-timescale-analytics-project</guid>
            <category><![CDATA[Announcements & Releases]]></category>
            <category><![CDATA[PostgreSQL]]></category>
            <category><![CDATA[Analytics]]></category>
            <dc:creator><![CDATA[David Kohn]]></dc:creator>
            <pubDate>Thu, 21 Jan 2021 03:16:15 GMT</pubDate>
            <media:content medium="image" href="https://timescale.ghost.io/blog/content/images/2021/01/alexander-andrews-4JdvOwrVzfY-unsplash.jpg">
            </media:content>
            <content:encoded><![CDATA[<p>We're excited to announce Timescale Analytics, a new project focused on combining all of the capabilities SQL needs to perform time-series analytics into one <a href="https://www.tigerdata.com/blog/top-8-postgresql-extensions" rel="noreferrer">Postgres extension</a>. Learn about our plans, why we're announcing them now, and ways to contribute your feedback and ideas.  </p><p>At Timescale, our mission is to enable every software developer to store, analyze, and build on top of their time-series data so that they can measure what matters in their world: IoT devices, IT systems, marketing analytics, user behavior, financial metrics, and more. To this end, we’ve built a <a href="https://www.timescale.com/products" rel="noreferrer">petabyte-scale, time-series database</a>.</p><p>Today, we’re excited to announce the Timescale Analytics project, an initiative to make Postgres the best way to execute critical time-series queries quickly, analyze time-series data, and extract meaningful information. SQL is a powerful language (we're obviously big fans ourselves), and we believe that by adding a specialized set of functions for time-series analysis, we can make it even better.</p><p>The Timescale Analytics project aims to identify, build, and combine all of the functionality SQL needs to perform time-series analysis into a single extension.</p><p><strong>In other words, the Timescale Analytics extension will be a "one-stop shop" for time-series analytics in PostgreSQL, and we're looking for feedback from the community: what analytical functionality would you find most useful?</strong></p><p>We believe that it is important to develop our code in the open and are requiring radical transparency of ourselves: everything about this project, our priorities, intended features, trade-off discussions, and (tentative) roadmap, are available in <a href="https://github.com/timescale/timescale-analytics">our GitHub repository</a>.</p><p>It is our hope that working like this will make it easier for the community to interact with the project and allow us to respond quickly to community needs. </p><p>To this end, we’re announcing the project as early as possible, so we can get community feedback before we become too invested in a single direction. Over the next few weeks, we’ll be gathering thoughts on initial priorities and opening some sample PRs. Soon after that, we plan to create an initial version of the Timescale Analytics extension for you to experiment with.</p><p>Here are some examples of analytics functions we are considering adding: monotonic counters, tools for graphing, statistical sketching, and pipelining.</p><h2 id="monotonic-counters">Monotonic Counters</h2><p>A monotonically increasing counter is a type of metric often used in time-series analysis. Logically, such a counter should only ever increase, but the value is often read from an ephemeral source that can get reset back to zero at any time (due to crashes or other similar phenomena). To analyze data from such a source, you need to account for these resets: whenever the counter appears to decrease, you assume a reset occurred, and thus, you add the value after the reset to the value immediately prior to the reset.</p><p>Assume we have a counter that measures visitors to a website.  If we were running a new marketing campaign focused on driving people to a new page on our site, we could use the change in the counter to measure the success of the campaign. While this kind of analysis can be performed in stock SQL, it quickly becomes unwieldy.</p><p>Using native SQL, such a query would look like:</p><pre><code class="language-SQL`">SELECT sum(counter_reset_val) + last(counter, ts) - first(counter, ts) as counter_delta 
FROM (
    SELECT *,
        CASE WHEN counter - lag(counter) OVER (ORDER BY ts ASC) &lt; 0
            THEN lag(counter) OVER (ORDER BY ts ASC)
            ELSE 0
        END as counter_reset_val
    FROM user_counter
) f;
</code></pre><p></p><p>This is a relatively simple example, and more sophisticated queries are even more complicated.</p><p><a href="https://github.com/timescale/timescale-analytics/issues/4">One of our first proposals for capabilities to include in Timescale Analytics</a> would make this much simpler, allowing us to  write something like:</p><pre><code class="language-SQL">SELECT delta(counter_agg(counter, ts)) as counter_delta FROM user_counter;</code></pre><p></p><p>There are many examples like this: scenarios where it’s <em>possible</em> to solve the problem in stock SQL, but the resulting code is not exactly easy to write, nor pretty to read.</p><p>We believe we can solve that problem and make writing analytical SQL as easy as any other modern language.</p><h2 id="tools-for-graphing">Tools for Graphing</h2><p>When graphing time-series data, you often need to perform operations such as <a href="https://en.wikipedia.org/wiki/Change_detection">change-point analysis</a>, <a href="https://medium.com/@hayley.morrison/sampling-time-series-data-sets-fc16caefff1b">downsampling</a>, or <a href="https://dawn.cs.stanford.edu/2017/08/07/asap/">smoothing</a>. Right now, these are usually generated with a front-end service, such as <a href="https://grafana.com/">Grafana</a>, but this means the graphs you use are heavily tied to the renderer you’re using. </p><p>Moving these functions to the database offers a number of advantages:</p><ul><li>Users can choose their graphing front-end based on how well it does graphing, not on how well it does data analytics</li><li>Queries can remain consistent across all front-end tools and consumers of your data</li><li>Doing all the work in the database involves shipping a much smaller number of data points over the network</li></ul><p>Key to getting this project working is building the output formats that will work for a variety of front-ends and identifying the necessary APIs. If you have thoughts on the matter, please hop on our <a href="https://github.com/timescale/timescale-analytics/discussions/30">discussion threads</a>.</p><p>A fully worked-out pure-SQL example of a downsampling algorithm is too long to include inline here (for example, a worked-through version of largest-triangle-three-buckets can be found in <a href="https://medium.com/@hayley.morrison/sampling-time-series-data-sets-fc16caefff1b">this blog post</a>) – but with aggregate support could be as simple as:</p><pre><code class="language-SQL">SELECT lttb(time, value, num_buckets=&gt;500) FROM data;</code></pre><p></p><p>This could return a <code>timeseries</code> data type, which could be ingested directly into a tool like Grafana or another language, or it could be unnested to get back to the time-value pairs to send into an external tool. </p><p>These tools can then use the simplified query instead of doing their own custom analysis on your data.</p><figure class="kg-card kg-image-card"><img src="https://timescale.ghost.io/blog/content/images/2022/01/Screen-Shot-2021-01-20-at-3.19.57-PM.png" class="kg-image" alt="Grafana dashboard UI, showing initial and downsampled data" loading="lazy" width="1600" height="944" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/Screen-Shot-2021-01-20-at-3.19.57-PM.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/Screen-Shot-2021-01-20-at-3.19.57-PM.png 1000w, https://timescale.ghost.io/blog/content/images/2022/01/Screen-Shot-2021-01-20-at-3.19.57-PM.png 1600w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://timescale.ghost.io/blog/content/images/2022/01/Screen-Shot-2021-01-20-at-3.18.43-PM.png" class="kg-image" alt="Grafana dashboard UI, showing initial and downsampled data" loading="lazy" width="1600" height="944" srcset="https://timescale.ghost.io/blog/content/images/size/w600/2022/01/Screen-Shot-2021-01-20-at-3.18.43-PM.png 600w, https://timescale.ghost.io/blog/content/images/size/w1000/2022/01/Screen-Shot-2021-01-20-at-3.18.43-PM.png 1000w, https://timescale.ghost.io/blog/content/images/2022/01/Screen-Shot-2021-01-20-at-3.18.43-PM.png 1600w" sizes="(min-width: 720px) 720px"><figcaption><span style="white-space: pre-wrap;">Example downsampling data from </span><a href="http://ecg.mit.edu/time-series/"><span style="white-space: pre-wrap;">this dataset</span></a><span style="white-space: pre-wrap;">. It keeps the large-scale features of the data, with an order of magnitude fewer data points</span></figcaption></figure><h2 id="statistical-sketching"><br>Statistical Sketching</h2><p>Sketching algorithms, such as <a href="https://github.com/timescale/timescale-analytics/issues/1">t-digest</a>, <a href="https://github.com/timescale/timescale-analytics/issues/3">hyperloglog</a>, and <a href="https://github.com/timescale/timescale-analytics/issues/6">count-min</a>, allow us to get a quick, approximate, answer for certain queries when the statistical bounds provided are acceptable.</p><p> This is even more exciting in the TimescaleDB ecosystem since it appears most of these sketches will fit nicely into <a href="https://docs.timescale.com/latest/using-timescaledb/continuous-aggregates">continuous aggregates</a>, allowing incredibly low query latency.  </p><p>For instance, a continuous aggregate displaying the daily unique visitors to a website could be defined like:</p><pre><code class="language-SQL">CREATE MATERIALIZED VIEW unique_vistors
WITH (timescaledb.continuous) AS
    SELECT 
    time_bucket('1 day', time) as day, 
    hll(visitor_id) as visitors
    FROM connections
    GROUP BY time_bucket('1 day', time);
</code></pre><p></p><p>Such a view could be queried to get the visitors over range of days, like so:</p><pre><code class="language-SQL">SELECT day, approx_distinct(visitors)
FROM unique_vistors
WHERE day &gt;= '2020-01-01' AND day &gt;= '2020-01-15'
</code></pre><p></p><p>Additionally, it would allow for re-aggregation to determine the number of unique visitors over a coarser time range, such as the number of monthly visitors: </p><pre><code class="language-SQL">SELECT time_bucket(day, '30 days'), approx_distinct(hll(visitors))
FROM unique_vistors
GROUP BY time_bucket(day, '30 days')
</code></pre><p></p><h2 id="pipelining">Pipelining</h2><p>SQL queries can get long, especially when there are multiple layers of aggregation and function calls.</p><p>For instance, to write a pairwise delta at minute-granularity in TimescaleDB, we’d use something like:</p><pre><code class="language-SQL">SELECT minutes, sampled - lag(sampled) OVER (ORDER BY minutes) as delta
FROM (
    SELECT
        time_bucket_gapfill(time, '1 minute') minutes,
        interpolate(first(value, time)) sampled
    FROM data
    GROUP BY time_bucket_gapfill(time, '1 minute')
) interpolated;
</code></pre><p></p><p>To mitigate this, the Timescale Analytics proposal includes a unified <a href="https://github.com/timescale/timescale-analytics/discussions/10">pipeline API</a> capability that would allow us to use the much more straightforward (and elegant) query below:</p><pre><code class="language-SQL">SELECT timeseries(time, value) |&gt; sample('1 minute') |&gt; interpolate('linear') |&gt; delta() FROM data;</code></pre><p></p><p>Besides the simpler syntax, this API could also enable some powerful optimizations, such as incremental pipelines, single-pass processing, and vectorization. </p><p>This is still very much in the design phase, and we’re currently having discussions about what such an API should <a href="https://github.com/timescale/timescale-analytics/discussions/10">look like</a>, what pipeline elements <a href="https://github.com/timescale/timescale-analytics/discussions/26">are appropriate</a>, and what the textual format <a href="https://github.com/timescale/timescale-analytics/discussions/10#discussioncomment-282898">should be</a>.</p><h2 id="how-we%E2%80%99re-building-timescale-analytics">How we’re building Timescale Analytics</h2><p>We’re building Timescale Analytics as a <a href="https://www.tigerdata.com/blog/top-8-postgresql-extensions" rel="noreferrer">PostgreSQL extension</a>. PostgreSQL's extension framework is quite powerful and allows for different levels of integration with database internals. </p><p>Timescale Analytics will be separate from the core  TimescaleDB extension. This is because TimescaleDB core interfaces quite deeply into PostgreSQL’s internals— including the planner, executor, and DDL interfaces—due to the demands of time-series data storage. This necessitates a certain conservatism to its development process in order to ensure that updating TimescaleDB versions cannot damage existing databases, and that features interact appropriately with PostgreSQL’s core functionality.</p><p>By separating the new analytics functionality into a dedicated Timescale Analytics extension, we can vastly reduce the contact area for these new functions, enabling us to move faster without increased risk. We will be focusing on improvements that take advantage of the PostgreSQL extension hooks for creating functions, aggregates, operators, and other database objects, rather those that require interfacing with the lower-level planning and execution infrastructure. Creating a separate extension also allows us to experiment with our build process and technologies, for instance, writing the extension <a href="https://github.com/zombodb/pgx">in Rust</a>.</p><p>More importantly,  we hope using a separate extension will lower barriers for community contributions. We know that the complexity of our integrations with PostgreSQL can make it difficult to contribute to TimescaleDB proper. We believe this new project will allow for much more self-contained contributions by avoiding projects requiring deep integration with the PostgreSQL planner or executor.</p><p>So, if you’ve been wanting to contribute back but didn’t know how or are a Rustacean looking to get involved in databasing, please join us!</p><h2 id="get-involved">Get Involved</h2><p>Before the code is written is the perfect time to have a say in where the project will go. To this end, we want—and need—your feedback: what are the frustrating parts of analyzing time-series data? What takes far more code than you feel it should? What runs slowly or only runs quickly after seemingly arcane rewrites?</p><p>We want to solve community-wide problems and incorporate as much feedback as possible, in addition to relying on our intuition, observation, and experiences.</p><p><strong>Want to help? </strong>You can submit suggestions and help shape the direction in 3 primary ways:</p><ul><li><a href="https://github.com/timescale/timescale-analytics/discussions"><strong>Look at some of the discussions</strong></a> we’re having right now and weigh in with your opinions. Any and all comments are welcome, whether you’re an experienced developer or just learning.</li><li><a href="https://github.com/timescale/timescale-analytics/labels/proposed-feature"><strong>Check out the features</strong></a> we’re thinking of adding, and weigh in on if they’re something you want, if we’re missing something, or if there are any issues or alternatives. We are releasing nightly Docker images of our builds.</li><li><a href="https://github.com/timescale/timescale-analytics/labels/feature-request"><strong>Explore our running feature requests, add a +1, </strong></a><strong> and </strong><a href="https://github.com/timescale/timescale-analytics/issues/new?assignees=&amp;labels=feature-request&amp;template=feature-request.md&amp;title="><strong>contribute your own</strong></a>.</li></ul><p><strong>Most importantly: </strong><a href="https://github.com/timescale/timescale-analytics/discussions"><strong>share your problems</strong></a><strong>! </strong>Tell us the kinds of queries or analyses you wish were easier, the issues you run into, or the workarounds you’ve created to solve gaps. (Example datasets are especially helpful, as they concretize your problems and create a shared language in which to discuss them.)</p><p><br></p>]]></content:encoded>
        </item>
    </channel>
</rss>