<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Preetam Jinka on Medium]]></title>
        <description><![CDATA[Stories by Preetam Jinka on Medium]]></description>
        <link>https://medium.com/@preetam_shiftleft?source=rss-9d69375466b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f4Jk_-T9cGmOWXSVLfc9Tg.jpeg</url>
            <title>Stories by Preetam Jinka on Medium</title>
            <link>https://medium.com/@preetam_shiftleft?source=rss-9d69375466b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 25 Nov 2026 02:35:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@preetam_shiftleft/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Browser-side Caching]]></title>
            <link>https://medium.com/shiftleft-blog/browser-side-caching-aa9427198153?source=rss-9d69375466b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa9427198153</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Preetam Jinka]]></dc:creator>
            <pubDate>Wed, 29 Sep 2021 13:03:10 GMT</pubDate>
            <atom:updated>2021-09-29T13:03:10.020Z</atom:updated>
            <content:encoded><![CDATA[<h3>Browser-side Caching for APIs</h3><h4>How ShiftLeft provides a snappy UI experience by caching API requests in the browser</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rfn9iZCk98F2dqeh" /><figcaption>Photo by <a href="https://unsplash.com/@wilhelmgunkel?utm_source=medium&amp;utm_medium=referral">Wilhelm Gunkel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>ShiftLeft Engineering uses an API-first implementation approach. We have a single, unified <a href="https://docs.shiftleft.io/api/">JSON REST API</a> used by our UI, CLI, integrations, custom scripts, and more. With so many dependencies, API performance and responsiveness is a clear priority for us.</p><p>Our UI is one API consumer that we pay extra attention to. It makes way more API requests than our CLI or other integrations. Clicking around the ShiftLeft dashboard and navigating through findings for different applications requires several API calls to load the required data, and those API calls may require expensive/long database queries.</p><p>Users may not notice their CI pipelines take a couple of seconds longer than usual, but every 100 ms counts when users are looking at spinners on their screen waiting for results of a scan to load. For many expensive requests, <strong>we let the browser cache the API response</strong>.</p><p><a href="https://www.shiftleft.io/">ShiftLeft</a> is a developer-friendly SAST platform that scans your code for security issues on every pull request. <strong>But if you’re not submitting new scans, your results don’t change, and we take advantage of that for caching</strong>. Here’s an example with the Applications dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tUEG0cEez6qvrqJ8DqSFg.png" /><figcaption>HTTP 304 Not Modified responses returned by the API</figcaption></figure><p>In the screenshot above, the initial page load calls the findings summary API endpoint which takes <strong>1.47 seconds</strong> and returns 65 KB of data. Subsequent requests take <strong>less than 0.1 seconds</strong> because there were no changes to the results.</p><h4>How it works: Last-Modified, If-Modified-Since, ETag, If-None-Match</h4><p>For a few expensive endpoints the API returns a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified">Last-Modified</a> header with a timestamp, and that lets your browser cache the API response. On the next request to that endpoint, your browser includes a <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-Modified-Since">If-Modified-Since</a> header with the same timestamp. We also send a hash of your applications list and scan IDs as part of the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ETag">ETag</a> header, which your browser sends back in the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/If-None-Match">If-None-Match</a> header.</p><p>If there are <em>no new scans, and no changes to the apps list </em>since that time, we stop early and return HTTP 304 Not Modified. This lets the browser use the cached response it already has, and our API avoids running expensive database queries.</p><p>Using just those 4 headers, we’re able to leverage browser-side caching and provide a fast UI experience for our users. The benefit of using browser-side caching is it is fast to implement, requires no additional infrastructure or storage on our backend, and no changes in our UI code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa9427198153" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shiftleft-blog/browser-side-caching-aa9427198153">Browser-side Caching</a> was originally published in <a href="https://medium.com/shiftleft-blog">ShiftLeft Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring a Live SaaS Environment]]></title>
            <link>https://medium.com/shiftleft-blog/refactoring-a-live-saas-environment-5d0911b8b281?source=rss-9d69375466b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d0911b8b281</guid>
            <category><![CDATA[saas]]></category>
            <category><![CDATA[static-code-analysis]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Preetam Jinka]]></dc:creator>
            <pubDate>Tue, 27 Oct 2020 15:17:18 GMT</pubDate>
            <atom:updated>2020-11-02T17:26:50.702Z</atom:updated>
            <content:encoded><![CDATA[<h4>We decided to refactor and re-implement almost all of our back-end and UI. This is how we went through the design and implementation. You can experience the new design by trying ShiftLeft code analysis product <a href="https://www.shiftleft.io/register?utm=as_blog_oct_2020">here</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*W_tSyNZ2TjwF04TK" /><figcaption>Photo by <a href="https://unsplash.com/@pilot218?utm_source=medium&amp;utm_medium=referral">Luka Slapnicar</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><a href="https://www.shiftleft.io/register?utm=as_blog_oct_2020">ShiftLeft NextGen Static Analysis</a> (NG SAST) is a software-as-a-service static analysis solution that allows developers to scan every pull request for security issues. Earlier this year we released Secrets, Security Insights, and a v4 API. Secrets and Security Insights are two new types of results we extract from code analysis, and the V4 API is a brand new RESTful JSON API with an OpenAPI/Swagger specification that you can use to access all of your results. Read more about these features in our <a href="https://blog.shiftleft.io/javascript-secrets-security-insights-and-apis-9ebf9bb87a37">announcement post</a>.</p><p>NG SAST was initially designed only for vulnerabilities. In order to implement Secrets and Security Insights, we either had to retrofit these new result types into our existing implementation or significantly refactor our back-end to support their unique characteristics. Even though it would take longer and be more difficult to implement, we decided to do the latter. We rewrote almost all of the storage used for storing code analysis results while maintaining backwards compatibility and without any outages. The analogy is that it’s like changing the engine on an airplane in flight without the passengers noticing.</p><p>We could’ve saved a lot of time by hacking things together and making it work, but instead chose to take a step back and use this opportunity to redesign, clean up some technical debt, and establish a solid foundation for future work. It wasn’t easy: in addition to re-implementing large parts of our back-end, the UI was also significantly refactored to move to a new API. It took several weeks of intense collaboration, designing, iterative implementation, and testing in production.</p><h3>Design</h3><p>With any big project, it’s impossible to jump into writing code. The Product team’s user stories paint a rough picture of what new features will ideally look like, but it’s the Engineering team’s job to take those requirements and translate them into implementation details. This requires a lot of back-and-forth, figuring out how all of the pieces fit together, what the edge cases are, and what’s possible or not possible to do within a given time frame.</p><h4>Process</h4><blockquote>As software engineers our job is not to produce code per se, but rather to solve problems. Unstructured text, like in the form of a design doc, may be the better tool for solving problems early in a project lifecycle, as it may be more concise and easier to comprehend, and communicates the problems and solutions at a higher level than code.<br><a href="https://www.industrialempathy.com/posts/design-docs-at-google/">https://www.industrialempathy.com/posts/design-docs-at-google/</a></blockquote><p>Every big engineering project at ShiftLeft starts as a design doc. These are Google Drive documents that describe what we want to implement and the implementation plan. This allows us to collaborate and iterate on a design with a large audience so everyone has an idea of and (a say in) what’s about to be implemented.</p><p>Even though only a handful of people were responsible for the implementation, the whole team participated in the review and refinement through design docs. One of the major objectives was to avoid any major surprises during implementation. A lot of time was spent on the design doc and API spec for this project, and as a result we ended up making lots of changes in the design in the beginning and had no major surprises.</p><h4>Data model</h4><p>We introduced two fundamental types: <em>scans</em> and <em>findings</em>. With <em>findings</em> we now have a generic data type to represent any kind of result we can get from code analysis. Vulnerabilities, Secrets, and Security Insights are now just different types of findings. Introducing <em>scans</em> allowed us to have an explicit data type representing each code analysis scan. This seems obvious to have, but it was implicit in the previous design: a scan was bits and pieces of information scattered around in different tables in our databases. Now we have tables literally called scans and findings!</p><blockquote>The right data model makes everything else easier.</blockquote><p>With the new data model, a lot of things became much easier. The mapping to database tables is more obvious, so database queries became much clearer, and in some cases, faster. It was much easier to implement certain features like tags, customizable severities, and scan comparison. Finally, when the data model is simpler you end up with fewer bugs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*u12qskvzcZ0aeqCNmY1GDw.png" /><figcaption>Vulnerabilities with user-friendly IDs</figcaption></figure><p>We were also able to implement user-friendly IDs for scans and findings. Instead of identifying them with long IDs or hashes, scans and findings now have GitHub-style incrementing numeric IDs. The first scan and finding of each project starts at ID 1, the second has ID 2, and so on. This was a feature that was requested by customers for a long time, and we finally had a easy way of implementing it with this refactor.</p><p>Some other features that depend on the new design:</p><ul><li>User-friendly API</li><li>User-friendly IDs for scans and findings</li><li>Expanded language support via <a href="https://blog.shiftleft.io/appthreat-is-joining-the-shiftleft-family-b9d95052aa50">ShiftLeft Scan</a></li><li>Better build rules that use the v4 API</li><li>Compare scans</li><li>Customizable severities and tags</li></ul><h4>Unified API</h4><p>The new v4 API that we implemented is a single API that is used by our UI and customers for their own scripts or integrations. Before there were two different APIs, v2 and v3, that are completely different. They had two different implementations and the one available to customers was very limited compared to what was used by the UI. With a single unified v4 API, we’re able to provide customers with all of the capabilities available through the UI for their own tools. From the back-end perspective, we only have a single API implementation to satisfy both use cases.</p><h3>Old and New</h3><p>Working with a live environment, we couldn’t just implement the new API and back-end and turn off the old one. First, there was a lot of data in the old format that we needed to migrate. In fact, it was also in a different database so we couldn’t just run a simple schema migration. Second, the UI needed to be rewritten for the new API too, and it was done in two phases so we needed to maintain support for the old API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CSqeHKKguQ8c5dgmMj-4wg.png" /></figure><p>We started by writing data from new customer scans to the old and new systems in parallel. Secrets and Security Insights are new features, so there wasn’t any old data for them, so they could be served only from the new API. Vulnerabilities had to be served from the old API because historical data wasn’t available to the new API.</p><p>As the UI was implemented using the new API, we slowly made bug fixes and added anything we missed during the initial implementation. Eventually, the new API was done, the UI was using it for Secrets and Security Insights, and it was time to get the last part of the new API working: Vulnerabilities.</p><h4>Data migration</h4><p>We had thousands of scans of vulnerability data in the old API back-end to migrate to the new API. We created a vuln_migration_status table to keep track of all of the past scans we needed to migrate. The following shows the schema for that table. sp_id is our old internal ID for scans.</p><pre>    Column       |           Type           | Nullable<br>-----------------+--------------------------+----------<br> sp_id           | text                     | not null<br> organization_id | text                     | not null<br> project_id      | text                     | not null<br> scan_id         | bigint                   | not null<br> processed_time  | timestamp with time zone |<br>Indexes:<br>    &quot;vuln_migration_status_pkey&quot; PRIMARY KEY, btree (sp_id)</pre><p>Next we created a small (&lt;250 line) Go script to iterate through this table and migrate vulnerabilities one scan at a time. It runs the same functions as the live production service to create scans and findings records, except with a timestamp in the past instead of the current time.</p><p>After a few hours of carefully running the migration in batches, we managed to migrate several thousands of scans with 0 failures! Even if we had a failure, we could keep track of our progress with the vuln_migration_status table and possibly skip over or manually fix any problematic scans. In the worst case, because the new data was only in new tables, we could have wiped everything and started over without any consequences.</p><h4>Feature flags</h4><p>Working on a SaaS platform makes it easy for us to deploy new features hidden by feature flags. This allows to iterate fast and incrementally ship to production, and also verify against live customer data. After migrating all of the old data and re-implementing the UI to use the new API, we had to make sure the results from the new API are the same as the old.</p><p>Our UI uses feature flags toggled by URL parameters. To enable the new views that work with the new API and back-end, we simply had to add ?findings=enable to the URL. This allowed us to compare results side-by-side.</p><p>This was one of the biggest projects at ShiftLeft. We decided to make changes to things that have been a certain way since the beginning of the company. It wasn’t an easy project, but there were several things that made it easier: a culture of collaboration, processes like design docs, and tooling like migration scripts and feature flags. Not only did this project give us a foundation for other features, but it also provided a template for working on other big projects too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d0911b8b281" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shiftleft-blog/refactoring-a-live-saas-environment-5d0911b8b281">Refactoring a Live SaaS Environment</a> was originally published in <a href="https://medium.com/shiftleft-blog">ShiftLeft Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Time Series at ShiftLeft]]></title>
            <link>https://medium.com/shiftleft-blog/time-series-at-shiftleft-e1f98196909b?source=rss-9d69375466b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1f98196909b</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[shiftleft]]></category>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[timescale]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Preetam Jinka]]></dc:creator>
            <pubDate>Wed, 05 Dec 2018 18:27:36 GMT</pubDate>
            <atom:updated>2018-12-05T23:25:22.517Z</atom:updated>
            <content:encoded><![CDATA[<p>Time series are a major component of the ShiftLeft runtime experience. This is true for many other products and organizations too, but each case involves different characteristics and requirements. This post describes the requirements that we have to work with, how we use <a href="http://bit.ly/2RCYjIF">TimescaleDB</a> to store and retrieve time series data, and the tooling we’ve developed to manage our infrastructure.</p><p>We have two types of time series data: metrics and vulnerability events. Metrics represent application events, and a subset of those that involve security issues are vulnerability events. In both cases, these time series have some sort of ID, a timestamp, and a count. Vulnerability events can also have an event sample that contains detailed information about the request that exercised a security vulnerability. In addition to those attributes, time series are also keyed by an internal ID we call an SP ID, which essentially represents a customer project at a certain version.</p><p>The data model for metrics is closely tied to the source-sink model of the <a href="https://blog.shiftleft.io/semantic-code-property-graphs-and-security-profiles-b3b5933517c1">Code Property Graph</a> such that, for a given application, its methods, and I/O and data flows are organized into triggers, inputs, and outputs. This has been illustrated in the figure below which summarizes a few typical endpoints acting as <em>trigger</em>s and the flows through which <em>input</em> data received at those endpoints eventually reach an <em>output </em>such as a log.We rarely query time series data for a single metric; usually we need to query for lots of metrics that are related according to this data model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*EFvFeNemC5zawA1_DCAwyQ.png" /><figcaption>Visualization of a flow and its trigger, input, and output ends</figcaption></figure><p>Here are the requirements that we’ve had to work with for the implementation:</p><ul><li>Needs to work with Go because almost all of the runtime infrastructure is written in Go.</li><li>Needs to fit in well with the rest of our development and testing environment. For example, our end-to-end (E2E) testing environment is implemented using <a href="https://docs.docker.com/compose/">Docker Compose</a> so all databases need to be available as a Docker image.</li><li>Has to support our rapid iteration workflow. We can’t be too tied down to a single data model as new features can change requirements.</li><li>Needs to be manageable by a small team. We’re a startup with limited resources so it would be best to choose a technology that is familiar to a lot of people.</li><li>Multiple granularity support and retention management so we can keep queries fast and costs low.</li></ul><p>So far we’ve found that TimescaleDB is the best suited for these requirements. <a href="http://bit.ly/2RxN4RF">TimescaleDB</a> is an open-source PostgreSQL extension that provides special tables called <em>hypertables</em> that behave like regular PostgreSQL tables but are partitioned into <em>chunks</em> under the hood. These chunks can be partitions of time as well as user-defined attributes. In our case we use SP ID as a partitioning column. This results in the the fast update and querying benefits of using several tables without the hassle of handling partitioning logic in your queries.</p><p>Our hypertables can have thousands of chunks. When we query for metrics for a given SP ID and time range, TimescaleDB filters out unnecessary chunks and only queries a small subset to execute the query. The other benefit of hypertables is we’re able to purge old data quickly by <a href="http://bit.ly/2Ryjg7g">dropping chunks</a> instead of running expensive DELETEs on large tables.</p><p>Finally, because we’re still working with PostgreSQL, we can leverage the development and operational experience we already have. We use other instances of PostgreSQL for some of our other SaaS data storage needs so we benefit from code reuse like <a href="https://blog.shiftleft.io/introducing-gaum-an-open-source-o-rm-that-isnt-an-o-rm-e7fd2880396e">Gaum</a>. There are also plenty of monitoring solutions that support PostgreSQL out-of-the-box.</p><h3>Infrastructure</h3><p>Almost all of ShiftLeft is deployed with Docker containers on an orchestration system. This includes TimescaleDB. We also use the Docker image for testing, and have a comprehensive E2E testing suite that uses Docker Compose.</p><p>Most of the ShiftLeft runtime infrastructure is written in Go. Runtime metrics data from agents ends up at gateway instances which publish into a Kafka topic. On the other side, we have consumer instances which ingest and aggregate the metrics data and occasionally write to TimescaleDB in batches. The minimum granularity is 2s, and we also have 1m and 5m aggregation in the consumers. ShiftLeft also has 1h and 1d granularity, but this is handled with a batch process instead.</p><h3>Rollups / Downsampling</h3><p>We created a period downsampling job to support larger granularities without aggregating in memory. On ingest, we periodically update a metrics_downsampling_status table which stores downsampling tasks.</p><p>Example data in the metrics_downsampling_status table:</p><pre>-[ RECORD 1 ]-----------------+------------------------------<br>sp_id                         | sl/b948474f-c0f1-4af...<br>granularity                   | 1h<br>time_bucket                   | 2018-08-17 14:00:00+00<br>last_processed_time           | 2018-08-17 18:16:20.939407+00<br>last_processed_duration       | 00:00:00.398403<br>data_last_added_to_time_range | 2018-08-17 14:40:30.188875+00<br>store                         | postgres<br>store_key                     | <br>-[ RECORD 2 ]-----------------+------------------------------<br>sp_id                         | sl/0fea1e78-30f6-494...<br>granularity                   | 1h<br>time_bucket                   | 2018-08-18 20:00:00+00<br>last_processed_time           | 2018-08-19 00:16:15.678155+00<br>last_processed_duration       | 00:00:00.561271<br>data_last_added_to_time_range | 2018-08-18 20:41:23.635222+00<br>store                         | postgres<br>store_key                     | <br>-[ RECORD 3 ]-----------------+------------------------------<br>sp_id                         | sl/006bef65-917d-4f3...<br>granularity                   | 1d<br>time_bucket                   | 2018-08-18 00:00:00+00<br>last_processed_time           | 2018-08-21 05:16:18.464218+00<br>last_processed_duration       | 00:00:00.573964<br>data_last_added_to_time_range | 2018-08-18 04:21:23.660622+00<br>store                         | postgres<br>store_key                     |</pre><p>Entries get updated in this table at the same time as our 5m aggregation flush. When the downsampling task runs, which happens once an hour, it looks for unprocessed rows in the status table, aggregates 5m data into 1h and 1d granularity, and then updates the status table again.</p><h3>Querying</h3><p>Our metrics API is written in Go, and it has logic to use the best granularity (or several) depending on the request. For example, requesting 60 points for a 5 hour interval means each point would be 5 minutes, so we can use our 5m granularity data. Anything smaller than a 5 hour range for 60 points means we have to use either 1m or 2s granularity. Aggregate counts (everything except charts) behave like charts but with 1 point.</p><p>Example of the granularity logic:</p><pre>[start, end, maxGranularity] := [0:36, 2:24, 1h]</pre><pre>0:00      1:00       2:00      3:00<br>+---------|----------|---------+<br>|     [.--|==========|--.]     |<br>+---------|----------|---------+<br>      ^                  ^<br>      |                  |<br>    Start               End</pre><pre>`.` =&gt; 1m<br>`-` =&gt; 5m<br>`=` =&gt; 1h</pre><pre>The returned slice should contain the following ranges:<br>* 1m granularity from 0:36 to 0:40<br>* 5m granularity from 0:40 to 1:00<br>* 1h granularity from 1:00 to 2:00<br>* 5m granularity from 2:00 to 2:20<br>* 1m granularity from 2:20 to 2:24</pre><p>One issue we had with queries was that sometimes a lot of time was spent on planning. In one case, we saw a query take 17 seconds for planning but only 250 ms on execution. This problem went away with <a href="https://github.com/timescale/timescaledb/blob/master/CHANGELOG.md#0100-2018-06-27">v0.10</a> which significantly improved chunk interaction for queries. You can read more about Timescale’s work on this improvement <a href="https://blog.timescale.com/optimizing-queries-timescaledb-hypertables-with-partitions-postgresql-6366873a995d">here</a>.</p><h4>Samples</h4><p>Vulnerability events can have details about requests like the HTTP path and headers. Some of these events are sampled and stored as JSON using a JSONB column in a hypertable. This way we get the flexibility of using JSON and unstructured data and the operational benefits of hypertables.</p><h3>Monitoring</h3><p>We monitor requests, TimescaleDB, and related components in several ways. To monitor query performance, we use a mix of <a href="https://github.com/ankane/pghero">PgHero</a> and application metrics. PgHero uses pg_stat_statements and provides a rough view of the top queries. In practice we usually don’t find it helpful because our queries tend to be fast and our request latency mainly comes from executing <em>lots</em> of these queries, not a single slow one. The majority of the time series metrics request monitoring is done with <a href="https://prometheus.io/">Prometheus</a> metrics exposed by the API and <a href="https://grafana.com/">Grafana</a> for visualization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*V7E5IXQVoJT68cSvH-XfUQ.png" /><figcaption>Average metrics latencies</figcaption></figure><p>In terms of ingest monitoring, we keep a close eye on DB write rates and latencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ff_wo9q5QDgO3FnbyLMTHg.png" /><figcaption>Database write rates</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YVPsHrt3SmdpmL5GLjR-Ig.png" /><figcaption>Average latency to flush metrics to TimescaleDB</figcaption></figure><p>We also use Grafana extensively with PostgreSQL, but for operational purposes and not extracting time series from hypertables. Using the <a href="http://docs.grafana.org/features/datasources/postgres/">PostgreSQL data source</a> option in Grafana, we can create visualizations based on queries against any PostgreSQL database. A couple of great examples are our downsampling charts. These use the metrics_downsampling_status table described earlier and let us keep an eye on pending work and processing times.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*wtDFCXx90IXF1xOy" /><figcaption>Monitoring the status of downsampling jobs using Grafana</figcaption></figure><p>Here’s what one of the SQL queries looks like for that Grafana chart:</p><pre><strong>SELECT</strong><br>  $__time(time_bucket),<br>  granularity || &#39;_unprocessed&#39; <strong>AS</strong> metric,<br>  -SUM(<strong>CASE WHEN</strong> last_processed_time <strong>IS NULL THEN</strong> 1 <strong>ELSE</strong> 0 <strong>END</strong>)<br>    unprocessed<br><strong>FROM</strong><br>  metrics_downsampling_status<br><strong>WHERE</strong><br>  $__timeFilter(time_bucket)<br><strong>GROUP BY</strong><br>  time_bucket, granularity<br><strong>ORDER BY</strong> time_bucket;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*CWkAHaYbLswR_Gvk" /><figcaption>Average downsampling job latency</figcaption></figure><p>When you zoom out to a longer time period like 90 days, you can clearly see some interesting trends. In our case, our downsampling tasks are starting to take longer and longer. They’re still around 2 sec on average so we don’t have any problems (yet).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*byrCUUBLhexoyI8Z" /><figcaption>Long-term downsampling latency trend</figcaption></figure><h3>What’s next</h3><p>We’ve been running this architecture using Kafka and TimescaleDB in production for a while and have done lots of different things with it in terms of feature use and monitoring. That said, there are still areas where we’re hoping to see improvement, both in how we manage our infrastructure and features that TimescaleDB can implement.</p><h4>How we can improve our infrastructure</h4><p><strong>Optimal chunk size:</strong> We haven’t determined what the optimal chunk size is, and we haven’t tried out adaptive chunking.</p><p><strong>Read replicas:</strong> We don’t use read replicas yet. We can easily improve our read query performance by adding a read replica and parallelizing requests.</p><p><strong>PostgreSQL 11:</strong> We’re still on PostgreSQL 9.6. PostgreSQL 11 introduces JIT compilation and evaluation of WHERE clauses which can really improve queries that have to filter lots of rows.</p><p><strong>Better ingest monitoring:</strong> We have a lot of visibility into PostgreSQL, but we don’t have visibility into what happens to metrics before PostgreSQL. For example, we’d like to have better metrics on how long it takes for a metric message to be accepted at the API until it makes it into TimescaleDB.</p><h4>What we’d like to see from TimescaleDB</h4><p><strong>RDS support:</strong> TimescaleDB is the only database we host ourselves. Our other PostgreSQL instances are hosted on RDS. We’d probably use RDS for everything if TimescaleDB was a supported extension.</p><p><strong>Compression:</strong> We could use ZFS for compression but we haven’t tried that yet. Compression is not a major requirement yet. It would be great if TimescaleDB supported that out-of-the-box.</p><p>All of this represents just a small part of the exciting work that’s happening in ShiftLeft Engineering. If these things sound interesting to you, come and <a href="https://www.shiftleft.io/careers">join us</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1f98196909b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shiftleft-blog/time-series-at-shiftleft-e1f98196909b">Time Series at ShiftLeft</a> was originally published in <a href="https://medium.com/shiftleft-blog">ShiftLeft Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>