<?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 Varun Mallya on Medium]]></title>
        <description><![CDATA[Stories by Varun Mallya on Medium]]></description>
        <link>https://medium.com/@vrnmallya?source=rss-5071631cc176------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Zt82K-fH0a95_-Or</url>
            <title>Stories by Varun Mallya on Medium</title>
            <link>https://medium.com/@vrnmallya?source=rss-5071631cc176------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 17:24:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vrnmallya/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[Realtime Data Drift Detection]]></title>
            <link>https://medium.com/dkatalis/realtime-data-drift-detection-140ff0d586ea?source=rss-5071631cc176------2</link>
            <guid isPermaLink="false">https://medium.com/p/140ff0d586ea</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[data-drift]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Varun Mallya]]></dc:creator>
            <pubDate>Wed, 27 Jul 2022 08:37:40 GMT</pubDate>
            <atom:updated>2022-08-01T04:18:45.351Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ok, maybe not “real-time” but mini online batch-based data drift detection.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbUUsZslldSf_Yw0uHLK7A.jpeg" /></figure><p>In the <a href="https://medium.com/dkatalis/data-drift-detection-in-kubeflow-pipelines-e38ef66767ca">last article</a>, we specified how to build a data drift component which could then be a part of the Kubeflow pipeline. But, what if your model is deployed as an API and you wish to perform a data drift detection alongside your inference? This is possible by using Evidently too!</p><p>Basically, for this use case, we would still need a reference dataset (the data the model was trained on). But, for the inference dataset, we will store samples of data we see during inference.</p><p>For example, let’s say we want a sample of size 100 to compare against the reference dataset. When the app starts, we will store 100 samples which may correspond to 100 API calls to a predict endpoint. We would compare it to the reference dataset and check for data drift only once we have 100 samples. From there, we would take the most recent 100 samples by dropping the least recent sample from our set for every subsequent API call.</p><p>Data drift is computed using this latest sample for every API call. The data drift metrics are exposed at the desired endpoint which can then be scraped by Prometheus and displayed via Grafana.</p><p>An example should make this easier to understand. The code for the same can be found<strong> </strong><a href="https://github.com/vmallya-123/evidently-real-time"><strong>in this repo</strong></a>.</p><p>We have a simple Fast API app which performs prediction. An endpoint for such an app can look like something shown below 👇🏽</p><pre>@app.post(&quot;/api/v1/predict&quot;)<br>async def predict_v1(data: PersonData):<br>    features = pd.DataFrame(data.dict(), index=[0])<br>    response = model.predict(features)<br>    return response</pre><p>PersonData holds the features which are then fed to the model to predict and the model response is returned. For identifying if this data has drifted from the data we saw in training, we have to set up drift monitoring.</p><p>To do this, first, we write a simple config file, mainly to initialise the drift-monitoring service:</p><pre>column_mapping: <br>  categorical_features:<br>  - job_title<br>  - industry<br>  - occupation<br>  numerical_features:<br>  - age<br>data_format:<br>  header: true<br>  separator: &#39;,&#39;<br>service:<br>  calculation_period_sec: 10<br>  monitors:<br>  - data_drift<br>  moving_reference: false<br>  reference_path: reference_df.csv<br>  use_reference: true<br>  window_size: 30</pre><p>This config file has column mappings which tell us which features are <strong>numerical</strong> and which are <strong>categorical</strong>. We set up the path of the reference_df this is the path of the training dataset. We also setup a minimum window size and calculation_period_sec.</p><p>Minimum window size gives us the size of the inference dataset which will be used to compute drift detection against reference data, whilecalculation_period_sec is the recurring time interval for data drift computation (i.e. compute drift detection every 10 seconds).</p><p>Once we have set up this config file, we need to initialise the data drift monitoring in the Fast API app by adding the below snippet of code:</p><pre>from realtime_data_drift.realtime_data_drift.data_drift import (getDriftMonitoringService,MonitoringService)<br>from starlette_exporter import PrometheusMiddleware, handle_metrics</pre><pre>app.add_middleware(<br>PrometheusMiddleware,<br>app_name=&quot;sample_fast_api&quot;,<br>prefix=&quot;sample_fast_api&quot;,<br>)</pre><pre>app.add_route(&quot;/metrics&quot;, handle_metrics)<br>SERVICE: Optional[MonitoringService] = None</pre><pre>@app.on_event(&quot;startup&quot;)<br>async def startup_event():<br>    global SERVICE<br>    config_file_name = &quot;data-drift-config.yaml&quot;<br>    if not os.path.exists(config_file_name):<br>        exit(&quot;Cannot find config file for the metrics service. Try to check README.md for setup instructions.&quot;)<br>    with open(config_file_name, &quot;rb&quot;) as config_file:<br>        config = yaml.safe_load(config_file)<br>    SERVICE = getDriftMonitoringService(config)</pre><p>We are going to set up Prometheus middleware so we can expose our metrics at <em>/metrics</em> endpoint. This can be achieved by using starlette_exporter. Once we have that, we initialise the monitoring service in the application startup. A good way to reuse the data drift monitoring across all API deployments would be to package it and store it in private PyPI. This <a href="https://github.com/vmallya-123/evidently-real-time/tree/master/realtime_data_drift">package</a> can then be imported across all models deployed via Fast API.</p><p>The last step is to use this service in the predict endpoint. So the endpoint we defined earlier would look something like this:</p><pre>@app.post(&quot;/api/v1/predict&quot;)<br>async def predict_v1(data: PersonData, background_tasks: BackgroundTasks):<br>    features = pd.DataFrame(data.dict(), index=[0])<br>    if SERVICE is None:<br>        logging.error(&quot;data drift service not found!&quot;)<br>    else:<br>    # drift will be computed when there is 30 rows of data<br>        background_tasks.add_task(SERVICE.iterate,   features.drop(&quot;person_id&quot;, axis=1))<br>   response = model.predict(features)<br>   return response</pre><p>We are using Fast API background task to compute data drift detection so that this does not impact the response time of the model prediction.</p><p>Once we run this app we will be able to see data drift metrics once we have enough data (window size of 30) i.e 30 requests to<em> /api/v1/predict</em> endpoint. The metrics will be available at<em> /metrics</em> endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*reddMJf4NSJyaaN8MBLuoQ.png" /></figure><p>This metrics endpoint would then have to be scraped by Prometheus scrape job. Once the metrics have been scraped then we can proceed to visualise this in Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HOBqxQDNYCweEry-h2iG3A.png" /></figure><p>The Grafana <a href="https://github.com/vmallya-123/evidently-real-time/blob/master/dashboard/data_drift.json">dashboard</a> is available in the repo and can be imported.</p><p>Do let me know what you think of Evidently’s drift detection package!</p><p><em>If you like to experiment with new ways to detect data drift, you might want to take a peek at </em><a href="https://www.dkatalis.co/jobs"><strong><em>our jobs board</em></strong></a><em>!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=140ff0d586ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dkatalis/realtime-data-drift-detection-140ff0d586ea">Realtime Data Drift Detection</a> was originally published in <a href="https://medium.com/dkatalis">DKatalis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Drift Detection In Kubeflow Pipelines]]></title>
            <link>https://medium.com/dkatalis/data-drift-detection-in-kubeflow-pipelines-e38ef66767ca?source=rss-5071631cc176------2</link>
            <guid isPermaLink="false">https://medium.com/p/e38ef66767ca</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kubeflow]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-drift]]></category>
            <category><![CDATA[mlops]]></category>
            <dc:creator><![CDATA[Varun Mallya]]></dc:creator>
            <pubDate>Mon, 30 May 2022 11:06:49 GMT</pubDate>
            <atom:updated>2022-06-20T09:06:37.751Z</atom:updated>
            <content:encoded><![CDATA[<h4>It is important to identify the drift at the earliest and take the necessary steps to mediate it.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3G6qezToVEXo8oHgz083kg.png" /></figure><p>We use Kubeflow pipelines to orchestrate our ML Pipelines. This includes training, inference, and backfilling of feature tables. Data drift is the variation in inference data from the data used during model training. It is important that we identify this at the earliest and take the necessary steps to mediate it.</p><p>One of the open-source tools used to identify data drift is <a href="https://evidentlyai.com/"><strong>Evidently</strong></a>. It runs statistical tests in the background to identify data drifts and provides a simple interface to run these tests. Evidently also provides interactive reports, which help us in debugging.</p><p>Our objective was to build a Kubeflow pipeline component which we could reuse across all our batch inference pipelines. This component needs 2 inputs, mainly:</p><ol><li>Reference Dataset</li><li>Inference Dataset</li></ol><p>This component’s output is a report that we can visualize in the Kubeflow pipelines UI.</p><p>You can find the component and the pipeline <a href="https://github.com/vmallya-123/kubeflow-evidently"><strong>in this repo</strong></a>.</p><p>The component checks if data drift has occurred by running the <a href="https://en.wikipedia.org/wiki/Kolmogorov%E2%80%93Smirnov_test#Two-sample_Kolmogorov%E2%80%93Smirnov_test"><strong>K-S test</strong></a>, which compares the two distributions(reference and inference dataset). The comparison is performed feature by feature. If a significant portion of features has drifted (in our case, it is 50% of the features), we can conclude that there is a significant data drift and we may need to retrain the model.</p><pre>def _detect_dataset_drift(<br>        reference,<br>        production,<br>        column_mapping,<br>        confidence=0.95,<br>        threshold=0.5,<br>        get_ratio=False,<br>    ) -&gt; bool:<br>        &quot;&quot;&quot;<br>        Returns True if Data Drift is detected, else returns False.<br>        If get_ratio is True, returns ration of drifted features.<br>        The Data Drift detection depends on the confidence level and the threshold.<br>        For each individual feature Data Drift is detected with the selected confidence (default value is 0.95).<br>        Data Drift for the dataset is detected if share of the drifted features is above the selected threshold (default value is 0.5).<br>        &quot;&quot;&quot;</pre><pre>data_drift_profile = Profile(sections=[DataDriftProfileSection()])<br>        data_drift_profile.calculate(<br>            reference, production, column_mapping=column_mapping<br>        )<br>        report = data_drift_profile.json()<br>        json_report = json.loads(report)<br>        #     return json_report<br>        drifts = []<br>        num_features = (<br>            column_mapping.numerical_features<br>            if column_mapping.numerical_features<br>            else []<br>        )<br>        cat_features = (<br>            column_mapping.categorical_features<br>            if column_mapping.categorical_features<br>            else []<br>        )<br>        for feature in num_features + cat_features:<br>            drifts.append(<br>                json_report[&quot;data_drift&quot;][&quot;data&quot;][&quot;metrics&quot;][feature][&quot;drift_score&quot;]<br>            )</pre><pre>n_features = len(drifts)<br>        n_drifted_features = sum([1 if x &lt; (1.0 - confidence) else 0 for x in drifts])</pre><pre>if get_ratio:<br>            return n_drifted_features / n_features<br>        else:<br>            if n_drifted_features / n_features &gt;= threshold:<br>                return True<br>            else:<br>                return False</pre><p>When we run this component in a pipeline we get the below dashboard under Kubeflow pipeline visualisation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IPWhOZg5hmcWvgYnuP1qVw.png" /></figure><p>We can use the results of this component to conditionally execute the rest of the pipeline if required.</p><p>The following blog post will showcase how we use Evidently for “real-time monitoring”, mainly for our models deployed as a Fast API service.</p><p><em>Meanwhile, if you find this article helpful and interesting, then maybe you would make a great fit for our team! </em><a href="https://www.dkatalis.co/opportunity"><strong><em>Join us</em></strong></a><em> and be a Katalis!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e38ef66767ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dkatalis/data-drift-detection-in-kubeflow-pipelines-e38ef66767ca">Data Drift Detection In Kubeflow Pipelines</a> was originally published in <a href="https://medium.com/dkatalis">DKatalis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubeflow with MLFlow]]></title>
            <link>https://medium.com/dkatalis/kubeflow-with-mlflow-702cf2ebf3bf?source=rss-5071631cc176------2</link>
            <guid isPermaLink="false">https://medium.com/p/702cf2ebf3bf</guid>
            <category><![CDATA[kubeflow]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[mlflow]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Varun Mallya]]></dc:creator>
            <pubDate>Fri, 27 May 2022 01:17:38 GMT</pubDate>
            <atom:updated>2022-06-13T09:31:18.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BtgMG7cmSdKMbhu_4GIhBg.jpeg" /></figure><p>Kubeflow and MLFlow are very well-known tools in the MLOps circle.</p><p>Kubeflow is a comprehensive ML Platform with features which range from auto ML to scheduling pipelines. MLFlow, on the other hand, works well as an artifact registry with a great experiment logging interface.</p><blockquote><strong>Kubeflow coupled with MLFlow is a marriage made in MLOps heaven</strong>.</blockquote><p><a href="https://github.com/vmallya-123/kubeflow-mlflow"><strong><em>Check out Github</em></strong></a></p><p>To begin we would first want to deploy MLFlow on k8s. This can be achieved like any other deployment. We start with a Dockerfile:</p><pre>FROM python:3.7-slim-buster<br><br>RUN pip3 install --upgrade pip &amp;&amp; \<br>    pip3 install mlflow==1.20.2 boto3 google-cloud-storage psycopg2-binary<br><br><br>ENTRYPOINT [&quot;mlflow&quot;,&quot; server&quot;]</pre><p>We are deploying our MLFlow on GKE with the GCS artifact store and Cloud SQL as the backend store. Please feel free to add any dependencies if you are deploying in a different environment.</p><p>Create a deployment.yaml:</p><p>Ensure that the env variables are passed via a config map or through some other means.</p><pre>apiVersion: v1<br>kind: ServiceAccount<br>metadata:<br>  name: mlflow-sa<br>  namespace: mlflow<br>---<br>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: mlflow-deployment<br>  namespace: mlflow<br>  labels:<br>    app: mlflow<br>spec:<br>  replicas: 1<br>  selector:<br>    matchLabels:<br>      app: mlflow<br>  template:<br>    metadata:<br>      labels:<br>        app: mlflow<br>    spec:<br>      serviceAccountName: mlflow-sa<br>      containers:<br>        - name: mlflow<br>          image: varunmallya/mlflow:latest<br>          imagePullPolicy: Always<br>          command: [&quot;/bin/bash&quot;]<br>          args:<br>            [mlflow server --host 0.0.0.0 --default-artifact-root ${MLFLOW_S3_ENDPOINT_URL} --backend-store-uri ${MLFLOW_TRACKING_URI}&quot;,<br>            ]<br>          ports:<br>            - containerPort: 5000</pre><p>And then, its corresponding service.yaml:</p><pre>apiVersion: v1<br>kind: Service<br>metadata:<br>  name: mlflow-service<br>  namespace: mlflow<br>spec:<br>  selector:<br>    app: mlflow<br>  ports:<br>    - protocol: TCP<br>      port: 5000<br>      targetPort: 5000</pre><p>MLFlow Deployed!</p><p>Now, we would like to have an MLFlow tab as part of the central dashboard in Kubeflow. To achieve this we need to define a virtual service which will make the MLFlow service available via Istio Ingress.</p><pre>apiVersion: networking.istio.io/v1beta1<br>kind: VirtualService<br>metadata:<br>  name: mlflow<br>  namespace: mlflow<br>spec:<br>  gateways:<br>  - kubeflow/kubeflow-gateway<br>  hosts:<br>  - &#39;*&#39;<br>  http:<br>  - match:<br>    - uri:<br>        prefix: /mlflow/<br>    rewrite:<br>      uri: /<br>    route:<br>    - destination:<br>        host: mlflow-service.mlflow.svc.cluster.local<br>        port:<br>          number: 5000</pre><p>Then we make a small change to the central dashboard config map:</p><pre>kubectl edit cm centraldashboard-config -n kubeflow<br># add this under the other menu items<br> {<br> “type”: “item”,<br> “link”: “/mlflow/”,<br> “text”: “MlFlow”,<br> “icon”: “icons:cached”<br> }</pre><p>After which we proceed to restart the central dashboard deployment</p><pre>kubectl rollout restart deploy centraldashboard -n kubeflow</pre><p>There you have it MLFlow nested within Kubeflow!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJu_zyWHJLeIKkMNDA4W9g.png" /></figure><p>Enjoy working, tinkering, and experimenting with MLFlow &amp; Kubeflow? <a href="https://dkatalis.co/jobs"><strong><em>Perhaps you would make an excellent fit for the team</em></strong></a><strong><em>!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=702cf2ebf3bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dkatalis/kubeflow-with-mlflow-702cf2ebf3bf">Kubeflow with MLFlow</a> was originally published in <a href="https://medium.com/dkatalis">DKatalis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Load Testing on K8s Using Locust]]></title>
            <link>https://medium.com/dkatalis/distributed-load-testing-on-k8s-using-locust-6ee4ed6c7ca?source=rss-5071631cc176------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ee4ed6c7ca</guid>
            <category><![CDATA[distributed-load-testing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[load-testing]]></category>
            <dc:creator><![CDATA[Varun Mallya]]></dc:creator>
            <pubDate>Fri, 03 Dec 2021 01:42:56 GMT</pubDate>
            <atom:updated>2022-01-03T07:22:41.709Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-EOCtsXsWKbfOH2S7WCT6Q.png" /></figure><p>One of the main objectives of load testing is to identify the maximum operating capacity of the application. We can simulate real load scenarios and understand how our system performs under such loads, test out if our application can scale and if the current setup has enough resources to support the load.</p><p>It will eventually help us to resolve issues that we may encounter in the future. For example, if we have a web app, we may want to identify the request latency time at peak load or find out what percentage of requests end up failing and if that is within our SLO.</p><p><strong>Github Repo</strong>: <a href="https://github.com/vmallya-123/learn-locus">https://github.com/vmallya-123/learn-locus</a>t</p><h3>Locust</h3><p>Locust is one of many open-source tools which aid in load testing. There are many other tools in the market like JMeter, Gatling, etc. However, Locust has some advantages over them, the biggest one being that the <em>locustfile </em>is just a regular Python file<em>.</em></p><p>A simple <em>locustfile</em> will be a list of tasks that simulate activities a user performs when he/she interacts with your app. There is no need to work with a different UI in setting up a load testing job. Another big plus point is that we can perform load testing in a distributed manner, with few additional lines of code. Locust comes with many features such as event hooks and messaging which helps in performing setup and communication between the master and workers (more on this later!).</p><h4>Load Testing Example</h4><p>Let us first have a <a href="https://github.com/vmallya-123/learn-locust/tree/main/webapp">small web app</a> against which we can perform our load test. This is a FastAPI app that has mainly two endpoints:</p><pre>@app.get(&quot;/&quot;)<br>async def hello(info : Request):<br>    return {&quot;Hello&quot;: &quot;World&quot;}</pre><pre>@app.post(&quot;/getInfo&quot;)<br>async def getInformation(info : Request):<br>    req_info = await info.json()<br>    return {<br>    &quot;status&quot; : &quot;SUCCESS&quot;,<br>    &quot;data&quot; : req_info<br>           }</pre><p>Now, let’s write a simple load test scenario. This small script can run a load test:</p><pre>from locust import HttpUser, task, between<br>import json</pre><pre>URL = f&quot;http://localhost:8000/&quot;</pre><pre>sample_data = {&quot;id&quot;: 123, &quot;name&quot;: &quot;Jay&quot;, &quot;city&quot;: &quot;Pune&quot;}</pre><pre>class APIUser(HttpUser):<br>    wait_time = between(1, 2)<br>    @task(1)<br>    def hello_world(self):<br>        self.client.get(URL)</pre><pre>    @task(2)<br>    def get_information(self):<br>        self.client.post(URL + &quot;getInfo&quot;, json.dumps(sample_data))</pre><p>We can run this by simply mentioning <em>locust</em> in the cli.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*oZVuDoMM0Y9GNZOI-bo0CQ.png" /></figure><p>This would point us to a UI where we can specify the test parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*ZNfovOBt9NOLhcS8jc5K7w.png" /></figure><p>Click on <em>Start swarming</em> to initiate your test!</p><p>Let us take a closer look at the <a href="https://github.com/vmallya-123/learn-locust/blob/main/simple/locustfile.py"><em>locustfile</em></a>. Mainly at the decorator <em>task </em>and<em> </em>function<em> between. </em>The task decorator is mainly used to list down the tasks, these are the endpoints a user will hit. We can see weights assigned to each task, in the example above we can see that <em>getInfo</em> task has two times the weight of “hello world” which makes Locust twice as likely to pick the <em>getInfo</em> task. To make a user sleep between sequential task execution we have <em>between </em>which will make the user sleep from 1 to 2 seconds before picking up the next task.</p><h4>Distributed Load Testing</h4><p>The above example can run on a single machine but sometimes we may need to run the load test in a distributed fashion. This may be when we have a complicated test plan or we want to generate even more load. Locust supports this.</p><p>Let us take another web app that has one endpoint which tells the file size. We will generate distributed load for this app. This setup involves one master and 5 workers. The role of the master is to divide the load between workers and keep track of their progress. In this case, the master will distribute the files equally between workers, and the workers will hit the app endpoint by downloading those files from a GCS bucket.</p><p>The setup would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/1*YCkV89icFpIolihEx_Zs5w.png" /></figure><p><a href="https://github.com/vmallya-123/learn-locust/blob/main/distributed/locust-tasks/locustfile.py"><em>locustfile</em></a> for distributed load testing has inbuilt event hooks:</p><pre><a href="http://twitter.com/events">@events</a>.init.add_listener<br>def on_locust_init(environment, **_kwargs):<br>    &quot;&quot;&quot;This runs on initialization of locust, before any test      starts&quot;&quot;&quot;<br>    <br>    logging.info(&quot;initializing locust message types and listeners&quot;)<br>    <br>    if not isinstance(environment.runner, MasterRunner):<br>        <br>        environment.runner.register_message(&quot;handle_files&quot;,     setup_workers)<br>    <br>    if not isinstance(environment.runner, WorkerRunner):<br>        <br>        environment.runner.register_message(&quot;acknowledge_file_recv&quot;,             on_acknowledge)</pre><p>Event hooks allow us to run code at specific time intervals. The above code, for example, runs when Locust is initialised. When Locust runs in a distributed environment, the same file is shared between workers and the master. However, we would still like to run some logic in the master but not in the workers. Locust allows us to differentiate between the two using the environment attribute, which informs us about the runner. The runner can be a MasterRunner, WorkerRunner or LocalRunner.</p><p>Locust also allows us to define messaging hooks by running <em>register_message</em>. These help us to communicate between Master and Worker. In the above function, we are registering two messages. One is of type <em>handle_files</em> and the other is <em>acknowledge_file_recv</em>. The handle files have a listener (<em>setup_workers</em>) associated with them, which runs every time it receives a message of that type.</p><p>Therefore, every time a worker receives a message of type <em>handle_files</em>, <em>setup_workers</em> runs and downloads the files from GCS to a local path. After a successful download, it sends a message back to the master informing that the file has been processed. This is done by sending a message to <em>acknowledge_file_recv</em>.</p><p>Think of the message types as <strong>topics</strong>. Internally, Locust is using ZeroMQ for communication.</p><pre>@events.test_start.add_listener<br>def on_test_start(environment, **_kwargs):<br>&quot;&quot;&quot;When the test is started, evenly divides list between</pre><pre>worker nodes to ensure unique data across threads&quot;&quot;&quot;</pre><pre>    if not isinstance(environment.runner, WorkerRunner):</pre><pre>        files = []</pre><pre>        for blob in storage_client.list_blobs(BUCKET_NAME):</pre><pre>        files.append(blob.name)</pre><pre>        worker_count = environment.runner.worker_count</pre><pre>        chunk_size = int(len(files) / worker_count)</pre><pre>        logging.info(f&quot;number of files to be divided between each  worker is {chunk_size}&quot;)</pre><pre>        for i, worker in enumerate(environment.runner.clients):</pre><pre>            start_index = i * chunk_size</pre><pre>            if i + 1 &lt; worker_count:</pre><pre>                end_index = start_index + chunk_size</pre><pre>            else:</pre><pre>                end_index = len(files)</pre><pre>            data = files[start_index:end_index]</pre><pre>            logging.debug(data)</pre><pre>            logging.debug(f&quot;sending this data {data} to this {worker}&quot;)</pre><pre>            environment.runner.send_message(&quot;handle_files&quot;, data, worker)</pre><p>The above event, as the name suggests, runs when we start a test. The code runs only in the master and it is dividing the files equally amongst the workers. It lists files that are present in the GCS bucket, and a subset of this list is shared amongst the workers. This is done by sending over the list to the <em>handle_files</em> topic.</p><p>After the files are downloaded by the workers to the local, they start running the task, i.e calling the API.</p><h4>Deploying On K8s</h4><p>First, we need to build our Locust docker image. In the example, you will notice a <a href="https://github.com/vmallya-123/learn-locust/blob/main/distributed/Dockerfile">DockerFile</a> under distributed folder. You can build an image by running:</p><pre>docker build . -t &lt;your_dockerhub_repo&gt;:&lt;tag&gt;</pre><p>To deploy on k8s we need 2 deployments and 1 service. The master and worker deployments, and service to expose the Master Web UI.</p><p>The manifests are placed under <a href="https://github.com/vmallya-123/learn-locust/tree/main/distributed/k8s">k8s</a> folder. There is a <em>kustomization</em> file that can be used to modify the image name. Currently, it is using a pre-built image. But if you change the code, make sure to build a new image. Once you have replaced the image name in <em>kustomization.yaml</em>, you can run:</p><pre>kustomize build distributed/k8s | kubectl apply -f -</pre><p>You can then access the Master UI by retrieving the external IP of the master service</p><pre>kubectl get svc locust-master</pre><p>Access the Master UI on port 8089. As we did for the non distributed example we specify the number of users, spawn rate and the host to initiate the load test.</p><h4>Running Without UI</h4><p>In some cases, we may want to run Locust without the UI; maybe when we want Locust to be part of the CI. This can be achieved with the following command:</p><pre>locust -f locustfile.py --headless -u 1000 -r 100 -H &lt;http://host-to-test</pre><p>Where <em>u</em> is the number of users to spawn, <em>r</em> is the rate at which the users are spawned per second. To run headless mode in a distributed setting, we need to specify <em>expect-workers</em> when we start the master worker. This tells the master to wait for the given number of workers before initiating the test</p><pre>locust -f locustfile.py --headless -u 1000 -r 100 -H &lt;http://host-to-test --expect-workers 5</pre><h4>Locust Test Results</h4><p>Interpreting Locust test results vary from use case to use case. In our case, we wanted to use Locust to mainly identify how our app would respond to high load.</p><p>The app in question is an ML app that accepts image files and returns annotations. We had arrived at peak load estimates and wanted to test our system against that load. During iteration, we identified some scaling issues which were rectified and got an estimate on request latency and expected number of failures. This helped us to understand the number of replicas we need to set up if we wish to keep the request latency and number of failures under a certain threshold.</p><h4>Exporting Metrics</h4><p>Locust web UI allows us to download the report of the test, and also retrieve the test metrics as a <em>csv </em>file by clicking on the <em>Download Data </em>tab<em>. </em>However, if you use Prometheus as your metrics DB, we can easily export the Locust metrics to Prometheus and use Grafana to visualise the load test metrics.</p><p>This can be done by using <a href="https://github.com/ContainerSolutions/locust_exporter">LocustExporter</a>. The master deployment needs an additional container that deploys the metrics exporter along with the master. To enable this, you have to deploy <a href="https://github.com/vmallya-123/learn-locust/blob/main/distributed/k8s/master-controller-with-metrics.yaml"><em>master-controller-with-metrics.yaml </em></a>instead of <a href="https://github.com/vmallya-123/learn-locust/blob/main/distributed/k8s/master-controller.yaml"><em>master-controller.yaml</em></a><em>.</em></p><p>There is also a Grafana <a href="https://grafana.com/grafana/dashboards/11985">dashboard</a> that comes along with the exporter.</p><h4>Conclusion</h4><p>Hopefully, this article can help you in setting up a load testing environment on K8s. Please let me know if you face any issues in the setup or if you have any burning questions!</p><p>If you like working with Kubernetes, crafting your own solutions, and wrangling Machine Learning Pipelines, then<em> </em><a href="https://dkatalis.co/jobs"><strong><em>maybe you would make an excellent fit for the team</em></strong></a><strong><em>!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ee4ed6c7ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/dkatalis/distributed-load-testing-on-k8s-using-locust-6ee4ed6c7ca">Distributed Load Testing on K8s Using Locust</a> was originally published in <a href="https://medium.com/dkatalis">DKatalis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>