<?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[Under the Microscope - Medium]]></title>
        <description><![CDATA[News and Views from the Engineering Team at PathAI - Medium]]></description>
        <link>https://medium.com/under-the-microscope?source=rss----72f579dbd84f---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Under the Microscope - Medium</title>
            <link>https://medium.com/under-the-microscope?source=rss----72f579dbd84f---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 10:18:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/under-the-microscope" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Prometheus Metrics for Batch Jobs on Kubernetes]]></title>
            <link>https://medium.com/under-the-microscope/prometheus-metrics-for-batch-jobs-on-kubernetes-b06ec3b620bc?source=rss----72f579dbd84f---4</link>
            <guid isPermaLink="false">https://medium.com/p/b06ec3b620bc</guid>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[batch-processing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Matthew Coleman]]></dc:creator>
            <pubDate>Sun, 16 Jun 2019 17:27:45 GMT</pubDate>
            <atom:updated>2019-06-17T18:31:39.774Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>PathAI’s core engineering work is built around scheduling, running, tracking, and otherwise managing compute jobs, usually as part of a machine learning pipeline. For Machine Learning Scientists and Engineers, the ability to experiment with data in a workflow without having to wrangle with underlying infrastructure (like monitoring or instrumenting metrics) while still having good observability into how their code is running is crucial to their projects going smoothly.</p><p>Collecting metrics about how code runs <a href="https://codeascraft.com/2011/02/15/measure-anything-measure-everything/">is not a new idea</a>, but most expertise is geared towards collecting and observing information about forever-running (usually web) services. What if you want to monitor finite, on-demand workflows, jobs, or data pipelines?</p><p>In this article, we provide a summary of how PathAI adopted existing technologies to give our developers the ability to measure things like training time, memory usage, data throughput (or almost anything) in a self-service way, and ultimately produce visualizations like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eu-77xRAwxN576RQoGh7gw.png" /><figcaption>Metrics generated as part of our machine learning pipeline.</figcaption></figure><h3>Getting Started</h3><p>A recent development in the industry is the meteoric rise of Kubernetes. From almost every perspective (Data, Platform, or ML Engineer), Kubernetes makes sense to adopt for batch work because of its fine-grained resource control, scheduling, and reliability enhancements. PathAI was already making heavy use of containers, so it made sense to adopt Kubernetes for our ML workloads.</p><p>The Kubernetes movement has also done a fantastic job of developing monitoring and metrics tooling that’s easy to integrate, feature-rich, and is relatively painless to adopt. <a href="https://prometheus.io/">Prometheus</a> is the technology leader in this space, providing both a capable time-series database (TSDB) for on-demand metrics storage and consumption, a rich query syntax, useful add-ons, client libraries for many languages, easy integration into Kubernetes, and even an alerting platform called Alertmanager.</p><p>Prometheus allows us to collect the data, but what about displaying it? Prometheus does come with a UI, but it is designed for people to test PromQL and doesn’t have the ability to build rich, interactive dashboards that can be saved for later. For this, <a href="https://grafana.com/">Grafana</a> is a natural choice. It has strong integrations with Prometheus as a data-source, is very feature-rich and flexible, and building and saving dashboards with it is easy to learn.</p><p>Now that we have our technology choices, we can start building a platform that makes it dead simple for any PathAI engineer to collect metrics directly from their code.</p><h3>Sampling Runtime in Jobs</h3><p>For batch processes, creating and saving metrics ends up being a little more work than metrics collection for long running services would be, mainly because Prometheus is “pull-based” rather than “push-based”. In other words, Prometheus expects to find some web endpoint exposed by your code where it can read in some data at its leisure. A batch process, on the other hand, lives, does its work, and then dies, and can’t be bothered to wait for a metrics platform to find an endpoint it’s exposing to collect information. Prometheus provides a solution for this with Pushgateway; a component that will cache metrics pushed to it for later consumption by Prometheus.</p><p>The crux of the work was then building a library into our ML code that easily allowed a developer to add a few lines and get a metric pushing to Pushgateway. Below is a walkthrough of what the work entailed.</p><h3>Building the Helper Library</h3><p>Firstly, setting up a connection with Pushgateway involved establishing a client connection and instantiating a “Collector Registry” that would receive metrics we produced in code. Our batch job logic exists as Python, so we placed the following in a Python module that we would expect to be imported wherever anyone wanted a metric.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8ce6469947c21adc50ed9cf9352b5ba/href">https://medium.com/media/f8ce6469947c21adc50ed9cf9352b5ba/href</a></iframe><p>Next, we wanted to define a relatively easy way to define an actual metric. Prometheus has several types of them, and if we had stopped here, a developer would have had to learn about the various metrics types and find one in the Python client library that fit their use case. However, we elected instead to build a helper method to deal with the minutiae of shipping a metric, without forcing the engineer to remember the intricacies.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87018db50d92b03e0b80ef167bd20fb4/href">https://medium.com/media/87018db50d92b03e0b80ef167bd20fb4/href</a></iframe><p>Each metric expects some basic information, such as the type of metric and some descriptive meta information Prometheus accepts. This helper method gives us the ability to do a few quality-control things, such as standardize the naming scheme of a metric and enforce some automatic labeling. The labels applied through the helper could do anything from identify which Kubernetes Node ran the batch job to which engineer or project the job belonged to.</p><h3>Creating an Actual Metric</h3><p>Now that we have a basic, shareable module, an ML Engineer just needs to do something like this, and everything should just work.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61895249a8236f699b01077f646b5ff0/href">https://medium.com/media/61895249a8236f699b01077f646b5ff0/href</a></iframe><p>This, however, isn’t enough to actually start moving data to Pushgateway — we still need to generate the actual data! This introduces another complication of metricizing batch processes rather than long-lived services — the Prometheus Python library doesn’t have a direct helper utility for generating something like elapsed time for Pushgateway metrics. No problem, we just added one to the helper library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b3a62c8fe0eeacdc52ce274baeff348d/href">https://medium.com/media/b3a62c8fe0eeacdc52ce274baeff348d/href</a></iframe><p>Here, we defined a Python function decorator that would actually supply data to our metric about how long the decorated function took to execute, which also automatically pushed the data. A couple things to note here: we decided to only allow Summary type metrics, as they make sense for “elapsed time” forms of data, we had to supply actual, contextual data through the decorator or through global scope (like “SOME_LABEL_VALUE,” “PUSHGATEWAY_URL” and etc.), and finally we had to make sure we didn’t push negative time (in the spirit of not trusting clocks).</p><p>Now we’re in business, and we can expand on the developer code example to show a timed function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34ee2dc14b05b456d64b18a6bb382e98/href">https://medium.com/media/34ee2dc14b05b456d64b18a6bb382e98/href</a></iframe><p>After developing this library, engineers on our ML team were able to produce over a dozen summary timers from their functions, measuring everything from training time, inference, and even things like S3 upload and download time.</p><h3>Will it Blend?</h3><p>Once metrics collection went live, it was important to let the metrics collection bake for some amount of time; making sure that data was accumulating and looked reasonable and to iron out any wrinkles. Two problems stood out.</p><ol><li>The reliability-minded of you have probably noticed that the code so far made the classic mistake of introducing a dependency on an external service and not accounting for its possible failure. Very quickly we realized we were crashing our training code every time we took Prometheus or Pushgateway offline. Metrics are like logs: ideally ML code, or any code, is ultimately more valuable than its measurement and should happily chug along even if it can’t record a metric.</li><li>Our Pushgateway server is behind HTTPS (which is good) but it’s using a certificate that’s signed by a CA not in the standard collection, which caused the Prometheus Python libraries to not want to actually make a connection. Figuring out this issue was probably the most challenging, but after some guidance in the Prometheus issue queue, we were able to define a “handler” for the connection that would successfully connect.</li></ol><p>The solution to both of these problems involved the same bit of code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2421de1a12c8f2ac9f7c4047b79da006/href">https://medium.com/media/2421de1a12c8f2ac9f7c4047b79da006/href</a></iframe><p>Here we actually copied a large chunk of the Prometheus Python client’s default handler and added some SSL manipulation, as well as a broad Exception catch for any metric that fails to write (logging a warning but preventing the program from stack tracing to death). Arguably we could have also solved the SSL problem more gracefully by manipulating system stored certs to add the root certificate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eH_sphQ9mQ4T53AZ7jxYDA.png" /><figcaption>Prometheus + Grafana + Kubernetes = Winning.</figcaption></figure><h3>Wrapping it Up</h3><p>In this post, we started with the goal of wanting to make metrics generation and telemetry dead simple for engineers who would rather just explore data about their code and not have to think too hard about how to produce and present it. We looked at the technologies available to us within the Kubernetes ecosystem, adopted Prometheus and Grafana, and set up some straightforward helper code that knows how to ship metrics to Prometheus using Pushgateway. If you’re looking to solve the same type of problem, hopefully these examples are useful.</p><p><em>Does this sound like interesting work? </em><a href="https://www.pathai.com/"><em>PathAI</em></a><em> is leveraging the latest in machine learning &amp; computer vision toward one of the most important problems facing us all, the diagnosis &amp; treatment of diseases like cancer. We’re currently about 70 employees, have raised over $75MM from top-tier investors, and are doing impactful work across life sciences, clinical practice, and global health.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b06ec3b620bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/under-the-microscope/prometheus-metrics-for-batch-jobs-on-kubernetes-b06ec3b620bc">Prometheus Metrics for Batch Jobs on Kubernetes</a> was originally published in <a href="https://medium.com/under-the-microscope">Under the Microscope</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using a CDN to Deploy Vue.js and Flask]]></title>
            <link>https://medium.com/under-the-microscope/using-a-cdn-to-deploy-vue-js-and-flask-93d5a2d623cc?source=rss----72f579dbd84f---4</link>
            <guid isPermaLink="false">https://medium.com/p/93d5a2d623cc</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[amazon-cloudfront]]></category>
            <dc:creator><![CDATA[Eleanor Mehlenbacher]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 00:11:59 GMT</pubDate>
            <atom:updated>2019-03-19T21:06:58.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently we added a UI on top of one of our machine-learning (ML) automation tools to give the ML team greater visibility into the inner workings of its pipelines. The original goal was to keep this UI as simple and straightforward as possible — we added a couple Flask endpoints to expose relevant data and used Bootstrap and jQuery to display everything — but over time, and with all the cool new CLI features, we’ve opted to rework that UI with <a href="https://vuejs.org/">Vue.js</a> and our internal design library Anodyne that’s used across the rest of PathAI’s applications.</p><p>This migration certainly improved the users’ experience, but it also helped us separate out the complicated deployment process of the backend with the expanding frontend. We could keep the existing Flask application and create a separate repo for the new Vue.js UI, complete with all of the testing frameworks and consistent design components that we didn’t have for the old UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IFbUbb7zAKLdgDlXGTMTsg.png" /><figcaption>The finished product!</figcaption></figure><p>This post describes how we set up a Vue.js frontend, coupled it with a Flask backend, and continue to manage the relevant static assets with AWS S3 and Amazon CloudFront.</p><h3>Getting started</h3><p>To have our Flask app serve up the Vue.js app, we needed to do a couple things:</p><ol><li>Use <a href="https://webpack.js.org/">Webpack</a> to bundle the Vue.js app into css/ and js/ directories that can be imported into the Flask app.</li><li>Put those bundled files somewhere accessible to the Flask app, and make the retrieval of those files fast and secure.</li><li>Configure the Flask app to fall back to the Vue.js router when a user accesses a page in the app.</li></ol><h3><strong>Bundling our Vue.js application</strong></h3><p>Luckily for us, Webpack is installed automatically when you use the <a href="https://cli.vuejs.org/">Vue.js CLI</a> to set up an application, so step 1 was as simple as running</p><pre>vue-cli-service build</pre><p>or</p><pre>yarn run build</pre><p>in the app’s directory. Webpack works as a module bundler for Javascript apps, as described <a href="https://webpack.js.org/concepts/">in its documentation</a>:</p><blockquote>when Webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.</blockquote><p>What this gives us is a convenient dist/ directory that houses a bundled version of the Vue.js app in the form of CSS and JS files.</p><h3><strong>Managing static assets with AWS</strong></h3><p>In the spirit of keeping our frontend and backend decoupled, we wanted to keep these bundled files somewhere that could be updated independently of backend changes. We use a number of <a href="https://aws.amazon.com/">AWS</a> services daily at PathAI for data storage, virtual environments, log management, etc., and we also already use <a href="https://aws.amazon.com/s3/">AWS S3</a> and Amazon’s content-delivery-network service <a href="https://aws.amazon.com/cloudfront/">CloudFront</a> to store and deliver static content for our client-facing products. Given the performance benefits provided by a CDN and the fact that we have existing methods in our Flask app for accessing/uploading data in S3, storing our bundled files there seemed like the most straightforward approach.</p><p>With each push to master in the Vue.js app’s repo, its CI pipeline can run tests on the app, run the Webpack build, and then push the contents of the newly created dist/ directory up to a designated bucket in S3, which will be accessible at a simple cdn.mydomain.com/&lt;bucket-name&gt;/&lt;file-name&gt;.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*7y5WKuvs0Z0S-8-2XSUfbw.png" /><figcaption>Just your average pipeline</figcaption></figure><p>Using a CDN definitely improves the time it takes to deliver static content to your browser, but one challenge in this solution was ensuring that the application is always receiving the latest version of the files. Our deploy script could have just built and replaced the bundled CSS/JS files in S3 each time we made changes to the UI, but if the Flask app is referencing the same file name, the contents of cdn.mydomain.com/&lt;bucket-name&gt;/main.css, for example, might remain <a href="https://aws.amazon.com/caching/cdn/">cached on the CDN</a> for some unforeseeable or undesirable amount of time — CloudFront defaults to 24 hours.</p><p>Older versions might also be <a href="https://css-tricks.com/strategies-for-cache-busting-css/">cached in the browser</a> if the file name remains the same. To make sure the user is always seeing the latest version of frontend code, we wrote a script that pushes up all of the CSS/JS files to S3 with unique names (like main.d708e4c2.css, generated during the Webpack build step) and includes a generated manifest.json file to identify which of the unique file names is the latest version:</p><pre><strong>{<br>    </strong>“css/app.css”: “css/app.27cee0c8.css”,<br>    “js/app.js”: “js/app.7bfe0aac.js”<br><strong>}</strong></pre><h3><strong>Integrating Vue.js with Flask</strong></h3><p>From the Flask side of things, we wanted the app to pull down the latest bundled frontend code every time the backend starts up, and preferably at some frequency afterwards, too. It can do this by reading the manifest.json file in S3 and generating the full link to the correct file version. With <a href="https://apscheduler.readthedocs.io/en/latest/">APScheduler</a>, this method can be called every ten minutes to update the file links when new frontend changes are pushed to master. The downside here is that the app won’t immediately notice new updates to our frontend code, but we felt that a ten-minute delay at most was acceptable; if an update needs to happen asap, we can always restart the Flask app to pull in the latest changes.</p><p>Here’s a simple version of this setup with only two files included in the manifest:</p><pre>import boto3<br>from apscheduler.schedulers.background import BackgroundScheduler</pre><pre># Update static frontend files to latest version from manifest (runs every 10 minutes)<br>def get_static_ui_files():<br>  with app.app_context():<br>    s3 = boto3.resource(‘s3’)<br>    manifest = s3.Object(‘bucket-name’, ‘manifest.json’).get()[‘Body’].read().decode(‘utf-8’)</pre><pre>    manifestJSON = json.loads(manifest)</pre><pre>    current_app._static_js = manifestJSON[‘js/main.js’]<br>    current_app._static_css = manifestJSON[‘css/main.css’]</pre><pre>get_static_ui_files()<br>scheduler = BackgroundScheduler()<br>scheduler.add_job(func=get_static_ui_files, trigger=’interval’, minutes=10)<br>scheduler.start()</pre><p>The last step is where we tell Flask to defer to the <a href="https://router.vuejs.org/guide/essentials/history-mode.html">Vue.js router</a> when users try to access the app. If a user enters a URL that doesn’t match any static assets or existing endpoints in the Flask app, a “catch-all” fallback route will serve up an index.html page including the CSS and JS files from our Vue.js app. We can use Flask’s render_template method to pass in the bundled file names we retrieved from the manifest:</p><pre>@app.route(‘/’, defaults={‘path’: ‘’})<br>@app.route(‘/&lt;path:path&gt;’)<br>def catch_all(path):<br>  with app.app_context():<br>    static_js = getattr(current_app, ‘_static_js’, None)<br>    static_css = getattr(current_app, ‘_static_css’, None)</pre><pre>    if (static_js is None or static_css is None):<br>      get_static_ui_files()</pre><pre>    return render_template(<br>      ‘index.html’,<br>      staticJS=current_app._static_js,<br>      staticCSS=current_app._static_css)</pre><p>And then our index.html template pulls in the static content:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=en&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;UI&lt;/title&gt;<br>    &lt;link href=”https://cdn.mydomain.com/{{ staticCSS }}” rel=stylesheet&gt;<br>  &lt;/head&gt;</pre><pre>  &lt;body&gt;<br>    &lt;div id=app&gt;&lt;/div&gt;<br>    &lt;script src=”https://cdn.mydomain.com/bucket-name/{{ staticJS }}”&gt;&lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The result is a spiffy new UI that’s consistent with the other Vue-based applications we build for our customers, significantly simpler to manage as a growing application, and much easier to navigate for the ML engineers who work with it every day. 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93d5a2d623cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/under-the-microscope/using-a-cdn-to-deploy-vue-js-and-flask-93d5a2d623cc">Using a CDN to Deploy Vue.js and Flask</a> was originally published in <a href="https://medium.com/under-the-microscope">Under the Microscope</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>