<?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 Naufal Al Hakim on Medium]]></title>
        <description><![CDATA[Stories by Naufal Al Hakim on Medium]]></description>
        <link>https://medium.com/@hakimnaufal?source=rss-352868fa89ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qIFSfGuFFXosXwCp3M8oYQ.jpeg</url>
            <title>Stories by Naufal Al Hakim on Medium</title>
            <link>https://medium.com/@hakimnaufal?source=rss-352868fa89ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:35:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hakimnaufal/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[Centralized Logging in Kubernetes with Vector]]></title>
            <link>https://medium.com/@hakimnaufal/centralized-logging-in-kubernetes-with-vector-0324475e9b55?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/0324475e9b55</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[startup]]></category>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 14:53:40 GMT</pubDate>
            <atom:updated>2026-03-24T14:55:06.669Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, at my new company we had a logging problem that sounds small until it’s not. Every pod clears its logs every 24 hours ( like any other pods do ). That’s it. If an error happens near that window, it’s gone. You’d have no idea it even happened unless you were watching at that exact moment. And ofc nobody is watching logs at 3am ( except you are a MAANG company with resources and money to do that and your service need to be 24/7, 365 days ).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*PfhEsU15bupew6Tf.gif" /></figure><p>So we started a RFC and PoC for centralized logging. Two hard constraints we had:</p><ol><li>Stay within free tier, and make it easy to swap platforms later (because you don’t want to be married to any one vendor forever).</li><li>We had about a week.</li><li>We don’t want to manage all the service related to logs, stack traces etc our own, since we only had a little team behind it.</li><li>and right now only logs. ONLY LOGS.</li></ol><p>I guess we have more than two constraint then eheheheh~~, and we ended up with <strong>Vector</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*17xrRIeWTicT4vXH.gif" /><figcaption>not this vector</figcaption></figure><h3><strong>What is Vector?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rEoCFwDMGckgRd51CItYdg.png" /><figcaption>thank you vector team for this</figcaption></figure><p><a href="https://vector.dev/"><strong>Vector</strong></a> is “a lightweight, ultra-fast tool for building observability pipelines.” Pretty much it collects logs from everywhere, transforms them using its own scripting language, and ships them to wherever you want to. The cool thing is it supports multiple sinks (destinations) at the same time, so you can send to BetterStack AND Loki AND AppSignal from one pipeline.</p><blockquote>TLDR: This “app” will “sit in the bottom” of your kubernetes pods and “collect” all the log data and send it to destinations. Pretty cool right?</blockquote><p>There are two architectures for running Vector in Kubernetes.</p><p><a href="https://vector.dev/docs/setup/going-to-prod/arch/agent/"><strong>Agent Architecture</strong></a><strong>: </strong>this is what we used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/0*IxKB1-DFOVUrhdbP" /><figcaption>agent p</figcaption></figure><p>Pretty much: pod → node log → Vector → sinks. Vector runs as a <strong>DaemonSet</strong> on every node, collecting logs from all the pods on that node.</p><p><a href="https://vector.dev/docs/setup/going-to-prod/arch/aggregator/"><strong>Aggregator Architecture</strong></a><strong>: </strong>you have a central Vector instance that receives from other Vectors or services. Good for large clusters but adds complexity we didn’t need it (since we are running 2–3 nodes, ofc we’re not going aggregator lol).</p><p>We used Helm to deploy since it would be easier since we already had helm inside our kubernetes env. And we fanned out logs to three sinks:</p><ol><li><strong>BetterStack</strong>: main logging platform, HTTP + Bearer Auth + gzip</li><li><strong>AppSignal</strong>: for the devs who live in AppSignal</li><li><strong>Grafana Loki: </strong>long-term retention and advanced querying</li></ol><p>Why these three? because these “sinks” provide the best “free-tier” right at that time. and these are what we got after a week of</p><h3>Getting Something Running</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*NOckPjE_xmqqKncf.gif" /></figure><p>We started with raw Vector YAML before touching Helm at all and oh boy I would not want to do it, yes direct config gives you full control but you lose reproducibility and secret management becomes a nightmare when you want staging vs production. We migrated to Helm pretty quickly.</p><p>The first real problem was noise. Raw Kubernetes logs are incredibly noisy health checks pinging every 10 seconds, Prometheus scraping /metrics, bots, readiness probes… if you send all of that to BetterStack you will burn through your free tier in hours ( and it did, i wasted the free-tiers in 5 minutes ). So we implemented filtering using <strong>VRL (Vector Remap Language) </strong>extensively, which is Vector&#39;s own DSL for transforming and filtering log events. It&#39;s pretty powerful but has a learning curve (more on that later).</p><h3>Filter Order Actually Matters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*PgL54WisrC8gAPwI.gif" /></figure><p>This surprised doesn’t surprise me. The sequence you apply filters in dramatically affects performance ( i didn’t check it, but ofc la you don’t need to think here ).</p><p>The order we landed on:</p><ol><li>Drop infrastructure logs first (kube-system, monitoring) highest volume</li><li>Drop metrics/Prometheus endpoints second highest</li><li>Drop bot traffic (AppSignalBot, UptimeRobot)</li><li>Drop health checks (/health, /readiness)</li><li>Service whitelist business logic filter</li><li>Log level filtering environment specific (drop debug logs in staging)</li></ol><p>Drop everything you need from the largest to the little thing, like a coffee filter, it would do the coarse in the top layer, and more condense through each layer.</p><p>Result: 95% of logs get filtered in the first two stages. The remaining filters barely do any work. If you put your whitelist filter first, you’re running business logic on every single log event instead of the 5% that survived infrastructure noise filtering.</p><p>We also reduced BetterStack log volume by about 60% just from tightening export criteria only send actionable logs, not every INFO that says &quot;request received.&quot;</p><h3>Multi-Sink and the Schema Incident</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*FfENBzDwZ9k36ipM.gif" /><figcaption>multi sink? multi confyushen</figcaption></figure><p>Adding AppSignal as a second sink was straightforward. Vector’s fan-out pattern is clean same log event goes to multiple destinations, each with its own filtering.</p><p>Then we made a mistake. We renamed the message field to payload because semantically it made more sense for our log structure.</p><p>It immediately broke downstream consumers, we reverted it and it came a okay, not every sink support the “same thing”. since BetterStack would auto convert the message to structured payload, it doesn’t mean it would support in AppStack and if you renamed it, it could not work in other sinks too.</p><h3>Loki and the Cardinality Trap</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*iDGP261VsujFEPLp.gif" /></figure><p>Adding Grafana Loki as a third sink was where I learned something I genuinely didn’t know before <strong>label cardinality in Loki is a hidden constraint</strong>.</p><p>We initially put the environment inside the service name label like service-staging and service-production. Makes sense right? Clean, readable, easy to query.</p><p>Nope.</p><p>Loki has limits on unique label combinations because each unique value creates a new index stream. service-staging and service-production are two completely separate streams in Loki&#39;s index. Multiply that by all your services and environments and you get cardinality explosion Loki performance tanks.</p><p>The fix:</p><pre>service_name = &quot;service-a&quot;     ← keep this stable<br>environment  = &quot;staging&quot;       ← use a separate label</pre><p>Simple but you’d only discover this after the performance degrades. The rule is: avoid dynamic labels. No timestamps, no request IDs, no user IDs as labels. Those belong in the log fields, not the stream labels.</p><p>Ohh and by doing this you’ll easily seperate the logs in grafana by using their filter env = staging</p><h3>Structured Logging</h3><p>If your services emit JSON logs, Vector can parse them and extract fields. So instead of a raw string you get queryable structured data in Grafana.</p><p>Before structured logging:</p><pre>{<br>  &quot;message&quot;: &quot;{\&quot;level\&quot;:\&quot;error\&quot;,\&quot;msg\&quot;:\&quot;DB connection failed\&quot;,\&quot;retry\&quot;:3}&quot;<br>}</pre><p>After:</p><pre>{<br>  &quot;message&quot;: &quot;{\&quot;level\&quot;:\&quot;error\&quot;,\&quot;msg\&quot;:\&quot;DB connection failed\&quot;,\&quot;retry\&quot;:3}&quot;,<br>  &quot;message_json&quot;: {<br>    &quot;level&quot;: &quot;error&quot;,<br>    &quot;msg&quot;: &quot;DB connection failed&quot;,<br>    &quot;retry&quot;: 3<br>  }<br>}</pre><p>Now you can write Loki queries like:</p><pre>{service_name=&quot;service-a&quot;} | json | level=&quot;error&quot; | retry &gt; 2</pre><p>This is soooo much better than trying to grep a string. My colleague implemented this one and it’s probably the change that made Grafana actually useful for our team.</p><h3>Production Hardening</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*KZs7YyweBNcpZIat.gif" /></figure><p>Compression numbers were honestly surprising. Adding gzip to BetterStack gave us ~70% bandwidth reduction for about 5% CPU increase. That’s an incredibly good trade-off. Snappy on Loki is optimized the other way faster at the cost of slightly less compression.</p><p>The other thing was jitter on retries. If all your Vector pods restart at the same time (say, during a deployment) and they all retry failed requests at the same interval, you will hammer your sink endpoints simultaneously. <strong>Thundering herd</strong>.</p><pre>retry_max_duration_secs: 300<br>retry_jitter_mode: &quot;full&quot;  # Random delay between 0 and max</pre><p>Smooth retry distribution, no cascading failures. I think I would have genuinely never thought of this if I hadn’t read the Vector docs carefully.</p><h3>The Challenges</h3><h3>VRL Debugging is Painful</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Ho5Fxq4Yg25w8_So.gif" /><figcaption>new things can be painful to start, watch, making it burn, and building it up again</figcaption></figure><p>VRL errors only show up in Vector pod logs, not at deploy time. You push a config, the pod starts, and only then do you find out your VRL syntax is wrong. And the pod is down, fear not it should be alright, but I still didn’t implement the “vrl validation” since ain’t nobody get time for that :) like everyone said, if it didn’t break then it shouldn’t be fixed :))</p><h3>Multiline Log Merging</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*3JQ7bAZlak9k7aPD.gif" /></figure><p>Stack traces get split into multiple separate log events by default. Each line of your Python traceback becomes its own event. So instead of one coherent error you get 20 separate entries with no clear relationship.</p><p>The VRL solution involves detecting continuation lines:</p><pre># Is this line a continuation of a previous log?<br>starts_with(.message, &quot; &quot;)  ||           # indented = continuation<br>starts_with(.message, &quot;\t&quot;) ||           # tab-indented<br>match(.message, r&#39;^\d{4}-\d{2}-\d{2}&#39;)  # timestamp prefix (docker)</pre><p>Impact: ~75% reduction in debugging time because you now get full error context in one event instead of hunting through 20 related entries.</p><h3>Service Whitelisting vs Blacklisting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*HpGpU0PWbRtcU7uX.gif" /></figure><p>We started with “log everything, blacklist noisy services.” This works right up until a new service gets deployed and you’re suddenly paying for its logs.</p><p>Better approach explicit whitelist:</p><pre>is_service_logged = contains(downcase(k8s_container), &quot;service-a&quot;) ||<br>                    contains(downcase(k8s_container), &quot;service-b&quot;) ||<br>                    contains(downcase(k8s_container), &quot;service-p&quot;) ||<br>                    contains(downcase(k8s_container), &quot;service-g&quot;)</pre><p>New services opt-in by default. Explicit cost control. Yikesssss would have been the alternative.</p><p>But oh boy I did wrong here using service whitelisting rather tahn blacklisting</p><h3>The Full Architecture</h3><pre>Kubernetes Pods (service-a, service-b, service-c, service-d…)<br>              ↓<br>  Vector DaemonSet (runs on every node)<br>    [1] kubernetes_logs source<br>    [2] merge_multiline  ← stack traces, panic messages<br>    [3] enrich           ← k8s metadata, environment, service_name, JSON parsing<br>    [4] Filter pipeline<br>         ├→ filter-nodes        (drop kube-system, monitoring)<br>         ├→ filter-metrics      (drop /metrics, prometheus)<br>         ├→ filter-bots         (drop AppSignalBot, UptimeRobot)<br>         ├→ filter-healthchecks (drop /health, readiness probes)<br>         ├→ filter-services     (keep only whitelisted services)<br>         └→ filter-logs         (drop debug in staging)<br>    [5] Multi-sink output<br>         ├→ BetterStack  (HTTP + Bearer Auth + gzip)<br>         ├→ AppSignal    (native sink + gzip)<br>         └→ Loki         (HTTP + Basic Auth + Snappy)</pre><p>Key numbers from the PoC:</p><ul><li>30 commits over 6 days</li><li>95% of logs filtered in first two stages</li><li>~67% overall cost reduction from filtering</li><li>~70% bandwidth reduction from compression</li><li>~75% reduction in debugging time from multiline merging</li></ul><h3>Results? One Month Later: We Dropped Everything…. Except a Few things…. Loki Grafana is the best :D</h3><p>Okay so after running this for about a month, we made a pretty big simplification: we dropped BetterStack and AppSignal and kept only Loki.</p><p>Why? Honestly pretty much because it covered everything we needed and it’s free. We already have Grafana. The Loki queries are good enough for our scale (we’re not Netflix). BetterStack is great but it’s paid beyond a certain volume and the plan that we want to use just gone, and AppSignal overlaps too much with what Lokialready gives us in Grafana and Sentry as well as UptimeRobot. So why maintain three sinks when one does the job.</p><p>On top of dropping two sinks we also rethink the filtering. And this is where it got cleaner.</p><h3>Namespace as the Primary Grouping Constraint</h3><p>The container name whitelist from the PoC was fine but it has a problem every time you add a new service you have to update the VRL. Miss it once and the new service either gets logged and costs you, or doesn’t get logged and you’re blind to its errors ( I think I could do this if we use CI/CD GitOps like argocd etc and everything ).</p><p>The better approach: <strong>filter by Kubernetes namespace instead of container name</strong>.</p><p>If all your application services live in, say, production and staging namespaces, you can just allowlist those two namespaces and you&#39;re done. Everything else kube-system, kube-public, kube-node-lease, all the AWS EKS namespaces (amazon-cloudwatch, aws-vpc-cni, kube-node-lease, whatever EKS decides to add) gets dropped automatically without you having to know their names.</p><pre># Only process logs from our application namespaces<br>allowed_namespaces = [&quot;production&quot;, &quot;staging&quot;]<br><br>if !includes(allowed_namespaces, string!(.kubernetes.namespace)) {<br>  abort<br>}</pre><p>And whoalaaa new service deployed into production? It&#39;s automatically in the pipeline. No VRL change needed. The namespace is your source of truth, not a manually maintained list of container names.</p><p>This also makes the filter pipeline simpler. You don’t need separate filters for kube-system, monitoring, bots, and infrastructure anymore. If it’s not in your namespace, it’s gone in one check at the top of the pipeline. The remaining filters only run on logs you actually care about.</p><h3>Per-Container Opt-Out via VRL</h3><p>Namespace filtering handles 99% of cases but sometimes you have a container inside your application namespace that you specifically want to exclude, maybe it’s a sidecar that generates a lot of noise, a debug container, or a job that runs on a schedule and spams logs you don’t need.</p><p>Instead of hardcoding container names into VRL (same problem as before), you can let developers opt-out by adding a label to their pod spec:</p><pre># in your pod spec<br>metadata:<br>  labels:<br>    logging: skip</pre><p>Then in VRL you just check for it:</p><pre># Respect per-pod opt-out label<br>if exists(.kubernetes.pod_labels.logging) &amp;&amp; .kubernetes.pod_labels.logging == &quot;skip&quot; {<br>  abort<br>}</pre><p>That’s it. The developer adds one label to their deployment manifest, Vector sees it and drops every log from that pod. No changes to the central Vector config, no PRs to the Helm chart, no coordination needed. It’s pretty much self-service opt-out.</p><p>The order matters here too put the namespace check first, then the label check. You’re already discarding the vast majority of events at the namespace filter, so the label check only runs on the small set of events that made it through.</p><h3>The Simplified Architecture</h3><pre>Kubernetes Pods (all namespaces)<br>              ↓<br>  Vector DaemonSet (runs on every node)<br>    [1] kubernetes_logs source<br>    [2] merge_multiline  ← stack traces, panic messages<br>    [3] filter-namespace ← drop everything not in production/staging  ← NEW<br>    [4] filter-label     ← drop pods with logging=skip label          ← NEW<br>    [5] enrich           ← k8s metadata, environment, service_name, JSON parsing<br>    [6] filter-metrics   ← drop /metrics, prometheus endpoints<br>    [7] filter-healthchecks ← drop /health, readiness probes<br>    [8] filter-logs      ← drop debug in staging<br>    [9] Loki only<br>         └→ Loki  (HTTP + Basic Auth + Snappy)</pre><p>Way fewer moving parts. The first two filters do almost all the work and the rest are fine-tuning. One sink means one thing to monitor, one set of credentials to rotate, one place to check when logs aren’t showing up, and of course it runs ever since, do we need to check it daily? ofc not, but now we have more than 1 days of log saved there and we can access it more than 7 days.</p><p>And gaaaly it’s the end of this, PoC and getting it implemented on production Okay bye y’all I’m going to take a sip of my matcha before the next implementation of “things” so, BYE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*cvcFLNHVxC7jfkSU.gif" /></figure><p>Okay here’s the complete vector-values.yaml more or less for the final Loki-only setup.</p><pre># vector-values.yaml<br># Helm chart: vectordotdev/vector v0.47.0<br># Image:      timberio/vector:0.51.0-debian<br>#<br># Before deploying run:<br>#   ./apply-template.sh &gt; vector-values-final.yaml<br>#   helm upgrade --install vector vectordotdev/vector \<br>#     --namespace vector --create-namespace \<br>#     --version 0.47.0 -f vector-values-final.yaml<br><br>role: Agent<br>image:<br>  repository: timberio/vector<br>  tag: &quot;0.51.0-debian&quot;<br># DaemonSet needs to run on every node including tainted ones<br>tolerations:<br>  - effect: NoSchedule<br>    operator: Exists<br># Small cluster (2-3 nodes)<br>resources:<br>  requests:<br>    memory: &quot;128Mi&quot;<br>    cpu: &quot;100m&quot;<br>  limits:<br>    memory: &quot;512Mi&quot;<br>    cpu: &quot;500m&quot;<br>customConfig:<br>  data_dir: /vector-data-dir<br>  sources:<br>    kubernetes_logs:<br>      type: kubernetes_logs<br>      self_node_name: &quot;${VECTOR_SELF_NODE_NAME}&quot;<br>  transforms:<br>    # [1] Merge multiline logs<br>    # starts_when fires when the line is NOT a continuation -<br>    # i.e. it doesn&#39;t start with whitespace or a stack frame prefix.<br>    # This keeps stack traces, panic messages, and error contexts<br>    # in a single event instead of 20 separate ones.<br>    merge_multiline:<br>      type: reduce<br>      inputs: [kubernetes_logs]<br>      group_by: [file, stream]<br>      merge_strategies:<br>        message: concat_newline<br>      starts_when:<br>        type: vrl<br>        source: |<br>          msg = string!(.message)<br>          !starts_with(msg, &quot; &quot;) &amp;&amp;<br>          !starts_with(msg, &quot;\t&quot;) &amp;&amp;<br>          !match(msg, r&#39;^\s+at &#39;) &amp;&amp;<br>          !match(msg, r&#39;^\s+File &quot;&#39;)<br>      expire_after_ms: 2000<br>      flush_period_ms: 500<br>    # [2] Namespace filter - primary inclusion gate.<br>    # Only pass logs from application namespaces.<br>    # Everything else (kube-system, kube-public, amazon-cloudwatch,<br>    # aws-vpc-cni, whatever EKS adds) is dropped in one check.<br>    # Add a namespace here when you add an environment - nothing else changes.<br>    filter_namespace:<br>      type: filter<br>      inputs: [merge_multiline]<br>      condition:<br>        type: vrl<br>        source: |<br>          allowed_namespaces = [&quot;production&quot;, &quot;staging&quot;]<br>          includes(allowed_namespaces, string!(.kubernetes.namespace))<br>    # [3] Per-pod opt-out.<br>    # Developers add label `logging: skip` to their pod spec to exclude<br>    # a noisy sidecar, scheduled job, or debug container.<br>    # No changes to this file needed - it&#39;s self-service.<br>    filter_label:<br>      type: filter<br>      inputs: [filter_namespace]<br>      condition:<br>        type: vrl<br>        source: |<br>          .kubernetes.pod_labels.logging != &quot;skip&quot;<br>    # [4] Enrich - add service_name, environment, parse JSON log bodies.<br>    enrich:<br>      type: remap<br>      inputs: [filter_label]<br>      source: |<br>        .service_name = downcase(string!(.kubernetes.container_name))<br>        .environment  = string!(.kubernetes.namespace)<br>        # If the log body is JSON, extract it so Grafana can query individual fields.<br>        parsed, err = parse_json(string!(.message))<br>        if err == null &amp;&amp; is_object(parsed) {<br>          .message_json = parsed<br>        }<br>    # [5] Drop metrics/prometheus scrape noise.<br>    filter_metrics:<br>      type: filter<br>      inputs: [enrich]<br>      condition:<br>        type: vrl<br>        source: |<br>          msg = downcase(string!(.message))<br>          !contains(msg, &quot;/metrics&quot;) &amp;&amp;<br>          !contains(msg, &quot;prometheus&quot;)<br>    # [6] Drop health check and readiness probe noise.<br>    filter_healthchecks:<br>      type: filter<br>      inputs: [filter_metrics]<br>      condition:<br>        type: vrl<br>        source: |<br>          msg = downcase(string!(.message))<br>          !contains(msg, &quot;/health&quot;) &amp;&amp;<br>          !contains(msg, &quot;/readiness&quot;) &amp;&amp;<br>          !contains(msg, &quot;/liveness&quot;) &amp;&amp;<br>          !contains(msg, &quot;healthz&quot;)<br>    # [7] Drop debug/trace in staging; pass everything in production.<br>    # Reads level from message_json if present, falls back to &quot;info&quot;.<br>    filter_logs:<br>      type: filter<br>      inputs: [filter_healthchecks]<br>      condition:<br>        type: vrl<br>        source: |<br>          if string!(.kubernetes.namespace) == &quot;staging&quot; {<br>            level = &quot;info&quot;<br>            if is_object(.message_json) {<br>              l, err = string(.message_json.level)<br>              if err == null { level = downcase(l) }<br>            }<br>            level != &quot;debug&quot; &amp;&amp; level != &quot;trace&quot;<br>          } else {<br>            true<br>          }<br>  sinks:<br>    loki:<br>      type: loki<br>      inputs: [filter_logs]<br>      endpoint: &quot;__LOKI_ENDPOINT__&quot;<br>      auth:<br>        strategy: basic<br>        user: &quot;__LOKI_USERNAME__&quot;<br>        password: &quot;__LOKI_PASSWORD__&quot;<br>      encoding:<br>        codec: json<br>      compression: snappy<br>      # Labels must be low-cardinality - no request IDs, timestamps, or user IDs.<br>      # environment + service_name is enough for most Grafana queries.<br>      labels:<br>        environment: &quot;{{ environment }}&quot;<br>        service_name: &quot;{{ service_name }}&quot;<br>        kubernetes_namespace: &quot;{{ kubernetes.namespace }}&quot;<br>        kubernetes_pod: &quot;{{ kubernetes.pod_name }}&quot;<br>      request:<br>        retry_max_duration_secs: 300<br>        retry_jitter_mode: &quot;full&quot;   # prevents thundering herd on mass restarts<br>        timeout_secs: 60</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0324475e9b55" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond the Cloud: Exploring Local LLMs on Android with Smolchat and Google AI Edge Gallery]]></title>
            <link>https://medium.com/@hakimnaufal/beyond-the-cloud-exploring-local-llms-on-android-with-smolchat-and-google-ai-edge-gallery-1fd10eb76b31?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fd10eb76b31</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Tue, 10 Jun 2025 15:02:09 GMT</pubDate>
            <atom:updated>2025-06-10T15:02:09.233Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been waiting for lower parameter Large Language Model to drop and one here it is. So if the parameter is low, we could run it on your phone. Like for real what if we could run it on your phone, NATIVELY of course Google did it first <a href="https://developer.android.com/ai/gemini-nano">https://developer.android.com/ai/gemini-nano</a> but what if you could do it using open model?</p><p>Our goals here to know is it possible to run LLM on your phone without the need of any other device or even provider such as Gemini, Claude and ChatGPT.</p><blockquote>Disclaimer, the lower your parameters the lower quality the output of anything from the LLM Model</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*lC7D2S1KO4jqSkicReiMYg.gif" /><figcaption>Me after any new model released</figcaption></figure><h3>Setting Up Our Experiment: Desktop vs. Mobile</h3><p>To truly understand the performance differences, we’ll run our tests on two distinct setups. First, we’ll leverage the power of our <strong>desktop machine</strong>, utilizing <strong>Ollama</strong> as our local AI runtime. This system boasts an <strong>AMD Ryzen 5 7600 6-Core Processor</strong> with <strong>12 threads</strong> and a substantial <strong>32GB of RAM</strong>, all running within <strong>WSL (Windows Subsystem for Linux)</strong>.</p><p>For our mobile comparison, we’ll turn to the <strong>Xiaomi 13T</strong>. This phone is powered by the <strong>MediaTek Dimensity 8200-Ultra</strong> chipset, built on an efficient <strong>4nm manufacturing process</strong>, complemented by <strong>12GB of RAM</strong>. This diverse hardware will give us a clear picture of how AI models perform across different computing environments.</p><blockquote>The prompt we are using across is<br>&gt; what is antibiotics and explain it</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtanwuECDzgBW_zgJeQU_Q.png" /><figcaption>Model initiated without running prompt</figcaption></figure><p>Before starting our prompt, we check the behavior of our resource using task manager and checked the memory usage, right now ollama didn’t use any of our resource (except memory for wsl).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GydRyYqpvsyXm6wconS1uw.png" /><figcaption>while prompted</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfZKVKXCfF9ntnZDCxwm7w.png" /><figcaption>Right after prompt end</figcaption></figure><p>When we initiated the process, the system’s resource consumption immediately surged. The <strong>CPU utilization</strong> jumped significantly, reaching <strong>60–70% across all cores</strong>, with individual core speeds hitting <strong>4.74GHz</strong>. Concurrently, <strong>RAM usage more than doubled</strong>, climbing from <strong>1.3GB to 3.5GB</strong>.</p><p>A detailed look at the ollama output provides further insights into this performance. The <strong>total duration</strong> for the operation was <strong>21.26 seconds</strong>, with the initial <strong>load duration</strong> taking <strong>1.47 seconds</strong>. The system processed the prompt, consisting of <strong>15 tokens</strong>, in just <strong>92.36 milliseconds</strong>, achieving a <strong>prompt evaluation rate of 162.42 tokens per second</strong>. Following this, the model evaluated <strong>983 tokens</strong> over <strong>19.69 seconds</strong>, resulting in an <strong>evaluation rate of 49.92 tokens per second</strong>. This data highlights the distinct phases of resource allocation during the operation, from initial loading and prompt processing to the more intensive token evaluation.</p><p>The output is this, so we would see something almost like this across all the platform we used.</p><pre>Okay, let’s break down antibiotics. Here&#39;s a comprehensive explanation, covering what they are, how they work, why<br>they’re important, and some important things to know:<br><br>**What are Antibiotics?**<br><br>Antibiotics are medications used to treat bacterial infections. They work by targeting and killing or inhibiting<br>the growth of bacteria. Think of them as specialized weapons against microscopic invaders.<br><br>**Why are they needed?**<br><br>Bacteria are incredibly diverse – some are harmless and some can cause serious illness.  Many infections are<br>caused by bacteria, and these infections can be very serious if left untreated. Antibiotics help us manage and<br>prevent these infections.<br><br>**How do Antibiotics Work?**<br><br>Here&#39;s a simplified breakdown of the process:<br><br>1. **Bacteria Respond to Antibiotics:** When you get an infection, your body produces bacteria to fight it off.<br>However, these bacteria often have unique defenses that antibiotics target.<br><br>2. **Antibiotics Disrupt Bacterial Processes:** Antibiotics don&#39;t work on viruses (like the cold or flu), so they<br>focus on stopping bacteria from:<br>   * **Reproducing:**  They kill or stop bacteria from making more copies of themselves.<br>   * **Growing:** They slow down the bacteria&#39;s growth.<br>   * **Spreading:**  They can prevent the bacteria from multiplying and spreading.<br><br>3. **Different Antibiotics Target Different Bacteria:** There are many different types of antibiotics, each<br>targeting specific types of bacteria. Some examples include:<br>   * **Penicillin:** Used against many bacterial infections, often skin infections.<br>   * **Amoxicillin:**  A common penicillin used to treat respiratory infections.<br>   * **Cephalosporins:** Used to treat a wider range of infections, including pneumonia.<br>   * **Azithromycin:** Often used to treat skin infections and some bacterial pneumonia.<br><br>**Important Note:** Antibiotics *don&#39;t* work against viruses. Taking antibiotics when you don&#39;t need them is a<br>major problem because it contributes to antibiotic resistance.<br><br>**Why are Antibiotics Important?**<br><br>* **Preventing Serious Infections:** Antibiotics are crucial for preventing serious infections caused by bacteria,<br>like:<br>    * Pneumonia<br>    * Strep throat<br>    * Skin infections (cellulitis)<br>    * Urinary tract infections (UTIs)<br>    * Food poisoning<br>* **Treating Infections:** They help to treat infections that would otherwise be life-threatening.<br><br><br>**The Problem with Antibiotic Resistance**<br><br>This is a *huge* concern.  Bacteria can evolve and change in response to antibiotics.  When antibiotics are used<br>too frequently, or they&#39;re used inappropriately, bacteria can:<br>* **Develop resistance:**  They change their surface proteins so that the antibiotic can&#39;t recognize them.<br>* **Mutate:**  Their genetic material changes, making them less susceptible to the drug.<br>* **Become less vulnerable:**  They can even lose the ability to survive the antibiotic.<br><br>**Important Considerations &amp; Responsible Use:**<br><br>* **Only Take for a Fever &amp; Symptoms:** Antibiotics are only effective against bacterial infections. Taking them<br>for a viral infection won&#39;t help and can be harmful.<br>* **Follow Your Doctor&#39;s Instructions:**  It’s critical to take the full course of antibiotics as prescribed, even<br>if you start feeling better.  Stopping early can lead to the infection returning or developing antibiotic<br>resistance.<br>* **Don&#39;t Share Antibiotics:** Antibiotics are a shared resource.  Sharing them can contribute to resistance.<br>* **Ask Your Doctor About Alternatives:**  Sometimes, there are alternative treatments, like supportive care<br>(rest, fluids, etc.) or observation, especially for certain infections.<br><br>**Disclaimer:** *I am an AI Chatbot and not a medical professional. This information is for general knowledge and<br>informational purposes only, and does not constitute medical advice. It is essential to consult with a qualified<br>healthcare professional for any health concerns or before making any decisions related to your health or<br>treatment.*<br><br>**Resources:**<br><br>* **World Health Organization (WHO):**<br>[https://www.who.int/news-room/q-a-detail/antibiotic-resistance](https://www.who.int/news-room/q-a-detail/antibioti[https://www.who.int/news-room/q-a-detail/antibiotic-resistance](https://wwwwho.int/news-room/q-a-detail/antibiotic-resistance)<br>* **Centers for Disease Control and Prevention (CDC):**<br>[https://www.cdc.gov/antibiotics/index.html](https://www.cdc.gov/antibiotics/index.html)<br><br>---<br><br>Would you like me to:<br><br>*   Explain a specific type of antibiotic in more detail?<br>*   Discuss the role of resistance in more detail?<br>*   Explore how antibiotics are used to treat a specific condition (like a bacterial skin infection)?</pre><h3><strong>Running LLM on Your Android Phone</strong></h3><p>Now we are going to do two different routes of trying to run open source model:</p><ol><li>Google AI Edge Gallery</li><li>Ollama (with extra steps).</li><li>SmolChat (using llama.cpp).</li></ol><h4>Google AI Edge Gallery</h4><p>The Google AI Edge Gallery is an experimental application that brings cutting-edge Generative AI models directly to your mobile device. Once the model is loaded, an internet connection isn’t required. Experiment with various models, engage in chats, ask questions with images, and discover new prompts, all powered by on-device AI.</p><p>Right now this application isn’t in Play Store/App Store but we could access the apk for it here <a href="https://github.com/google-ai-edge/gallery/releases/tag/1.0.3">https://github.com/google-ai-edge/gallery/releases/tag/1.0.3</a></p><p>Google AI Edge Gallery pretty much the google attempt almost like smolchat but with google spice put into it.</p><p>You just need to download the app, open it, and download the model you want. You could use the model provided in the list or manually download it via huggingface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GmMOx7t6p31Rz1S5Y0S1Eg.png" /><figcaption>AI Chat in Google AI Edge</figcaption></figure><p>Now let’s test it out.</p><p>Right now we are not seeing the usage of the hardware such as RAM usage and CPU usage directly but we could see the total duration from the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hNyagup1ZzXBGb045zFhdg.png" /><figcaption>Model configs, output and stats using GPU</figcaption></figure><p>The screenshots provide a clear view of an AI chat application running in dark mode. The left panel, labeled “Model configs,” shows adjustable parameters for the AI model, including “Max tokens” (set to 1024), “TopK” (64), “TopP” (0.95), and “Temperature” (1.00). Users can also choose their desired accelerator, with “GPU” currently selected over “CPU.”</p><p>The right screenshot displays the AI chat interface, where a query “what is antibiotics and explain it” has been entered. Below the chat output, a “Stats on GPU” section is visible. This performance overlay indicates the following metrics:</p><ul><li><strong>1st token:</strong> 0.67 seconds</li><li><strong>Profil speed:</strong> 8.90 tokens/s</li><li><strong>Decode speed:</strong> 14.47 tokens/s</li><li><strong>Latency:</strong> 17.67 seconds</li></ul><p>These statistics offer insight into the model’s responsiveness and processing efficiency when utilizing the GPU for accelerated inference. The bottom of the interface consistently features a text input field for new prompts.</p><p>Output</p><pre>**Antibiotics: What They Are**<br>Antibiotics are powerful medications that fight bacteria infections.<br>They work by inhibiting bacterial growth and killing bacteria.<br>Here&#39;s what&#39;s important:<br>*   **Bacteria:** They&#39;re microscopic organisms essential for many processes like digestion and health.<br>*   **Bacteria Infections:** They can cause infections like urinary tract infections (UTIs), respiratory infections (like pneumonia or bronchitis), skin infections,<br>*   **Antibiotics work by interfering with bacteria&#39;s ability**<br>*   **How They Work:** They work by disrupting bacterial cell walls or blocking their ability<br>*   **Common Uses:** They&#39;re used as an overall treatment and may be prescribed to treat infection<br>Let&#39;s look at various types:<br>*   **Penicillins:** Used against bacteria with an &#39;P&#39; on their name.<br>*   **Cephalosporins:** Used against bacteria<br>*   **Macrolides:** Like azithromycin or erythromycin used against bacteria<br>*   **Tetracyclines:** Used against bacteria.<br>Do you want me provide examples?</pre><p>If you are using CPU accelerator,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rUs94Rz_TUybDcjdAFkOLw.png" /><figcaption>Model configs, output and stats using GPU</figcaption></figure><p>The provided screenshots illustrate an AI chat application in dark mode, similar to the previous analysis. The left image shows the input field with the query “what is antibiotics and explain it” and the on-screen keyboard. Crucially, a “Configs updated” notification is visible at the top, indicating that the model parameters are set to: Max tokens (1024), TopK (64), TopP (0.95), and Temperature (1.00). In this instance, the <strong>“CPU” accelerator is selected</strong>.</p><p>The right screenshot displays the AI’s detailed response to the query. Below the generated text, a “Stats on CPU” section provides the following performance metrics when running on the CPU:</p><ul><li><strong>1st token:</strong> 0.95 seconds</li><li><strong>Prefill speed:</strong> 6.32 tokens/s</li><li><strong>Decode speed:</strong> 14.45 tokens/s</li><li><strong>Latency:</strong> 32.86 seconds</li></ul><p>These statistics provide valuable insights into the model’s performance characteristics, specifically how quickly it generates the first token, its prefill and decode speeds, and overall latency when processing the request using the device’s CPU. The total elapsed time for this particular interaction is also noted as 32.9 seconds.</p><p><a href="https://github.com/google-ai-edge/gallery">GitHub - google-ai-edge/gallery: A gallery that showcases on-device ML/GenAI use cases and allows people to try and use models locally.</a></p><h4><strong>Smolchat routes</strong></h4><p><a href="https://github.com/shubham0204/SmolChat-Android">GitHub - shubham0204/SmolChat-Android: Running any GGUF SLMs/LLMs locally, on-device in Android</a></p><p>Smolchat primary goal is to deliver a <strong>highly intuitive and user-friendly interface</strong> that facilitates seamless interaction with <strong>local Small Language Models (SLMs)</strong> directly on the user’s device. This eliminates the need for an internet connection, ensuring privacy and rapid response times.</p><p>The application empowers users with full control over their SLM ecosystem. It will allow them to <strong>easily add and remove SLMs (specifically GGUF models)</strong>, providing flexibility in model choice. Furthermore, users will have the ability to <strong>customize the behavior of these models</strong> by modifying their system prompts and fine-tuning inference parameters such as temperature and min-p.</p><p>Smolchat right now is in Play Store and github, both can run and do the same thing. Almost the same step with Google AI Gallery, you just need to download the app, open it, and download the model you want. You could use the model provided in the list or manually download it via huggingface.<br><a href="https://play.google.com/store/apps/details?id=io.shubham0204.smollmandroid">https://play.google.com/store/apps/details?id=io.shubham0204.smollmandroid</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQtLpj50DHYIs3rjmOeoXA.png" /><figcaption>Smolchat user interface</figcaption></figure><p>Now let’s test it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3koT-tFn9uanebYKiAv6OQ.png" /><figcaption>Our test using smolchat</figcaption></figure><p>Smolchat offer a comprehensive look at the settings and performance of an on-device AI chat application. The left screenshot, titled “Edit Chat Settings,” displays various configurable parameters for the loaded language model. An initial unlabeled slider is set to <strong>0.05</strong>. The <strong>Temperature</strong> parameter, which controls the randomness of outputs, is set to <strong>1.0</strong>, suggesting a more creative and diverse generation style.</p><p>The <strong>Context Size</strong> for the model is configured to <strong>2048 tokens </strong>and can do more, indicating the maximum number of tokens the model considers for its input and output sequence. It’s more than the google platform that is 1024 tokens. Performance metrics indicate a <strong>generation speed of 17.06 tokens/s</strong>, with the overall operation completing in <strong>41 seconds</strong>. This detailed view provides insight into both the software configurations and the real-world resource utilization and speed of the local SLM.</p><p>Output</p><pre>Okay, let&#39;s talk about antibiotics! It&#39;s a really important topic, and I&#39;ll explain it to you in a way that&#39;s easy to understand.<br>**What are Antibiotics?**<br>Essentially, antibiotics are **medications that kill bacteria** – that&#39;s the key! They’re a specific type of drug that helps our bodies fight off infections caused by bacteria.  Bacteria are tiny living organisms that are everywhere – in our bodies (helping us digest food), in the soil, and even in the water we use.<br>**Why do we need antibiotics?**<br>Our bodies don&#39;t always fight off infections on their own.  Bacteria can cause problems, like:<br>*   **Strep Throat:**  A nasty infection that makes your throat sore.*   **Urinary Tract Infections (UTIs):** Infections in the bladder, urethra, or vagina.*   **Mouth Infections:**  Can cause pain and affect your ability to eat and drink.*   **Skin Infections:**  Like boils or infected cuts.*   **Food Poisoning:**  Sometimes caused by bacteria in food.<br>**How do Antibiotics work?**<br>Antibiotics work by targeting specific parts of bacteria that are important for them to survive.  They typically do this in a few ways:<br>1.  **Disrupt Cell Walls:** Bacteria have a tough outer layer called the cell wall. Antibiotics can weaken this wall, making the bacteria vulnerable to our immune system.2.  **Interfere with DNA:**  Bacteria have a very specific genetic code they use to make their own cells and grow. Antibiotics can disrupt this code, causing the bacteria to essentially &quot;shut down&quot; and die.3.  **Inhibit Enzymes:** Bacteria produce enzymes that are important for building and repairing their bodies. Antibiotics can block these enzymes, stopping the bacteria from growing and reproducing.<br>**Important Things to Know About Antibiotics:**<br>*   **They&#39;re NOT effective against viruses:** Antibiotics only work against bacteria.  They can&#39;t help with things like the cold, flu, or the things that cause a rash.*   **Side Effects:**  Antibiotics can cause side effects like nausea, stomach upset, and allergic reactions.*   **Antibiotic Resistance:** This is a big problem!  When bacteria become resistant to antibiotics (meaning they don&#39;t respond to them), it&#39;s like giving them a super-charged attack.  Doctors need to be careful when prescribing antibiotics, and they often need to use combinations of drugs, or new ways to target the bacteria.*   **Important:  Don&#39;t take antibiotics without a doctor&#39;s prescription!**  They&#39;re prescribed for a specific reason.  Taking antibiotics without a doctor&#39;s guidance can be harmful.<br>**Disclaimer:** *I am an AI Chatbot and not a medical professional. This information is for general knowledge and should not be considered medical advice. Always consult with a qualified healthcare professional for any health concerns or before making any decisions related to your health or treatment.*<br>---<br>**Do you want me to go into more detail about any particular aspect of antibiotics? For example, would you like to know:**<br>*   More about different types of antibiotics?*   How they&#39;re used in specific situations (like a really serious infection)?*   Something else entirely?</pre><h3>Mobile vs Mobile</h3><p>Upon comparing these results, several observations can be made regarding the trade-offs between GPU and CPU processing on the mobile device:</p><ul><li><strong>Initial Responsiveness (1st token):</strong> The <strong>GPU demonstrates superior initial responsiveness</strong>, generating the first token in 0.67 seconds compared to the CPU’s 0.95 seconds. This suggests the GPU is faster at the very beginning of the generation process.</li><li><strong>Decode Speed:</strong> Both the GPU and CPU (in the second test) achieved very similar decode speeds, at <strong>14.47 tokens/s and 14.45 tokens/s respectively</strong>. Interestingly, the third CPU test (with Q2_K model and specific settings) showed a <strong>slightly higher decode speed of 17.06 tokens/s</strong>. This could be attributed to the specific Q2_K quantization of the model, the enabled mmap option, or the explicit thread count optimization for the CPU.</li><li><strong>Overall Latency/Total Duration:</strong> This is where the most significant difference lies. The <strong>GPU completed the task much faster with an overall latency of 17.67 seconds</strong>. The CPU, in the second test, took almost twice as long at <strong>32.86 seconds</strong>. The third CPU test, despite a potentially faster decode speed, had the longest total duration at <strong>41 seconds</strong>.</li></ul><h3>Overall Comparison and Summary</h3><p>This comparison clearly illustrates the current landscape of local AI inference across different hardware platforms:</p><ul><li><strong>Raw Processing Power:</strong> The <strong>desktop PC holds a significant advantage in raw processing power and overall throughput</strong>. Its higher CPU clock speeds, greater core/thread count, and larger RAM capacity allow it to evaluate and generate tokens at a rate approximately 2–3 times faster than the mobile phone’s best performance. The total task completion time on the desktop (21.26s for 983 tokens) is notably shorter than the phone’s CPU-based times (32.86s to 41s), and even competitive with the phone’s GPU time (17.67s for potentially fewer tokens).</li><li><strong>User Responsiveness:</strong> Both platforms offer good initial responsiveness. The PC’s prompt evaluation is incredibly fast, while the mobile phone’s GPU-accelerated first token generation is very quick (0.67s), which is important for a snappy user experience.</li><li><strong>Hardware Utilization:</strong> The desktop effectively utilized its CPU, peaking at 60–70%. The phone, while more resource-constrained, demonstrates efficient use of both its GPU and CPU for AI tasks, with the GPU offering a clear advantage in overall latency compared to the CPU for the same model. Optimized CPU settings on the phone can boost decode speed, but may still result in longer overall task durations depending on the query length.</li></ul><p><strong>Implications for Local AI:</strong></p><ul><li><strong>Desktop:</strong> Ideal for <strong>more demanding or longer AI generation tasks</strong> where maximum throughput is critical, or for developing and fine-tuning models. The use of ollama further streamlines local model management.</li><li><strong>Mobile Phone:</strong> While not matching desktop speeds, the phone’s performance, particularly with GPU acceleration, highlights the <strong>increasing viability of running sophisticated AI models directly on consumer devices</strong>. This enables powerful, private, and offline AI capabilities for everyday use cases, such as conversational AI, local image analysis, or text summation, without reliance on cloud services. The trade-off is generally a longer wait time for more extensive outputs.</li></ul><p>As you have known PC provides a <strong>high-performance environment for rapid and large-scale SLM inference</strong>, leveraging its robust hardware to deliver impressive token generation rates and low overall task duration. While, the <strong>mobile phone showcases the growing accessibility and practical utility of on-device AI</strong>, demonstrating that even with less powerful hardware, it can offer a surprisingly responsive and completely offline AI experience, especially when utilizing its dedicated GPU for acceleration.</p><p>The choice between platforms depends on the specific use case: the desktop for power and speed, and the mobile phone for portability, privacy, and immediate, on-the-go AI capabilities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fd10eb76b31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trying out VLLM + DeepSeek R1 in Google Colab: A Quick Guide]]></title>
            <link>https://medium.com/@hakimnaufal/trying-out-vllm-deepseek-r1-in-google-colab-a-quick-guide-a4fe682b8665?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4fe682b8665</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[google-colab]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deepseek]]></category>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 07:37:11 GMT</pubDate>
            <atom:updated>2025-01-29T07:39:13.369Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I experimented with running DeepSeek R1 distilled with Qwen 7B locally without any GPU. All my CPU cores and threads were pushed to their limit, reaching the highest temperature of 90 degrees Celsius (Ryzen 5 7600).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*Ng3JeXVcnAO70PEMJBJg_Q.gif" /><figcaption>my cpu running ollama deepseek-r1 distilled qwen 7b</figcaption></figure><p>My friend said why didn’t you use Google Colab? since it gave you a GPU (for 3–4 hours for free). He’s been using it for RAG app parsing pdf with more than 80 pages and chaining LLM since we can still abuse (use) google colab.</p><p>And I did, I got a taste of T4 (20-series) with caveats (I’ll explain it later, TL:DR because it’s free). So I’ve been using it to test VLLM in Google Colab. Using FastAPI and ngrok for exposing the API to the public (for testing purposes because why not right?).</p><p>Okay time to explain everything and why I did it.</p><p>(WARNING THIS IS JUST FOR TESTING PURPOSES).</p><h4>PIP (Pip Install Package).</h4><p>It allows you to install and manage additional libraries and dependencies that are not included in the standard Python library. Right now we’re going to install it using the CLI by passing ! into the code of Jupyter Notebook.</p><pre>!pip install fastapi nest-asyncio pyngrok uvicorn<br>!pip install vllm</pre><p>We will install FastAPI, nest-asyncio, pyngrok, and Uvicorn as the Python services that will handle requests from external sources. VLLM is primarily the library for LLM inference and serving. While Ollama is an option, I believe this approach will be more effective.</p><h4>Now we are going to interact the VLLM function.</h4><pre># Load and run the model:<br>import subprocess<br>import time<br>import os<br><br># Start vllm server in the background<br>vllm_process = subprocess.Popen([<br>    &#39;vllm&#39;,<br>    &#39;serve&#39;,  # Subcommand must follow vllm<br>    &#39;deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B&#39;,<br>    &#39;--trust-remote-code&#39;,<br>    &#39;--dtype&#39;, &#39;half&#39;,<br>    &#39;--max-model-len&#39;, &#39;16384&#39;, # This is max token input and output that you send and retrieve<br>    &#39;--enable-chunked-prefill&#39;, &#39;true&#39;,<br>    &#39;--tensor-parallel-size&#39;, &#39;1&#39;<br>], stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)</pre><p>Okay so this is how I load the model, by starting vllm server in the background since if you are in Jupyter Notebook it will stuck in the process running the vllm and we cannot expose it (I think we can, but I just do this instead). In here we can see</p><ol><li>— trust-remote-code, so it trusts the remote code.</li><li>— dtype, half to reduce memory usage.</li><li>— max-model-len, for max token input + output combined that you want to send and retrieve.</li><li>— enable-chunked-prefill, refers to the process of <strong>preloading</strong> tokens into the model before generation starts.</li><li>— tensor-parallel-size, splits the model <strong>across multiple GPUs</strong> to speed up inference.</li></ol><p>By doing this we are not going to get the limit of T4 since</p><ul><li>Watch out for CUDA out-of-memory errors (we’re limited with 15GB of VRAM)</li><li>Colab’s GPU memory constraints might require parameter adjustments</li><li>12 GB of RAM, it’s enough….. I think.</li></ul><p>Now run it.</p><h4>Subprocess</h4><p>Okay since we are using subprocess and using start_new_session to true, we cannot normally pipe the output, if there is error we cannot see it until it errored out.</p><pre>import requests<br><br>def check_vllm_status():<br>    try:<br>        response = requests.get(&quot;http://localhost:8000/health&quot;)<br>        if response.status_code == 200:<br>            print(&quot;vllm server is running&quot;)<br>            return True<br>    except requests.exceptions.ConnectionError:<br>        print(&quot;vllm server is not running&quot;)<br>        return False<br><br>try:<br>    # Monitor the process<br>    while True:<br>        if check_vllm_status() == True:<br>            print(&quot;The vllm server is ready to serve.&quot;)<br>            break<br>        else:<br>            print(&quot;The vllm server has stopped.&quot;)<br>            stdout, stderr = vllm_process.communicate(timeout=10)<br>            print(f&quot;STDOUT: {stdout.decode(&#39;utf-8&#39;)}&quot;)<br>            print(f&quot;STDERR: {stderr.decode(&#39;utf-8&#39;)}&quot;)<br>            break<br>        time.sleep(5)  # Check every second<br>except KeyboardInterrupt:<br>    print(&quot;Stopping the check of vllm...&quot;)</pre><p>It will check every 5s and tried to piped the output if there is an error or will print vllm stderr and out. if the vllm is all good then you could proceed to the next block of code.</p><h4>Creating Function Call vLLM</h4><pre>import requests<br>import json<br>from fastapi import FastAPI, HTTPException<br>from pydantic import BaseModel<br>from fastapi.responses import StreamingResponse<br>import requests<br><br># Request schema for input<br>class QuestionRequest(BaseModel):<br>    question: str<br>    model: str = &quot;deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B&quot;  # Default model<br><br><br>def ask_model(question: str, model: str):<br>    &quot;&quot;&quot;<br>    Sends a request to the model server and fetches a response.<br>    &quot;&quot;&quot;<br>    url = &quot;http://localhost:8000/v1/chat/completions&quot;  # Adjust the URL if different<br>    headers = {&quot;Content-Type&quot;: &quot;application/json&quot;}<br>    data = {<br>        &quot;model&quot;: model,<br>        &quot;messages&quot;: [<br>            {<br>                &quot;role&quot;: &quot;user&quot;,<br>                &quot;content&quot;: question<br>            }<br>        ]<br>    }<br><br>    response = requests.post(url, headers=headers, json=data)<br>    response.raise_for_status()  # Raise exception for HTTP errors<br>    return response.json()<br><br># Usage:<br>result = ask_model(&quot;What is the capital of France?&quot;, &quot;deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B&quot;)<br>print(json.dumps(result, indent=2))<br><br>def stream_llm_response(question:str, model:str):<br>    url = &quot;http://localhost:8000/v1/chat/completions&quot;<br>    headers = {&quot;Content-Type&quot;: &quot;application/json&quot;}<br>    data = {<br>        &quot;model&quot;: model,<br>        &quot;messages&quot;: [{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: question}],<br>        &quot;stream&quot;: True  # 🔥 Enable streaming<br>    }<br><br>    with requests.post(url, headers=headers, json=data, stream=True) as response:<br>        for line in response.iter_lines():<br>            if line:<br>                # OpenAI-style streaming responses are prefixed with &quot;data: &quot;<br>                decoded_line = line.decode(&quot;utf-8&quot;).replace(&quot;data: &quot;, &quot;&quot;)<br>                yield decoded_line + &quot;\n&quot;</pre><p>We have two API for testing,</p><h4>ask_model function</h4><p><strong>Purpose:</strong><br>Sends a request to the vLLM server and waits for a full response.</p><p><strong>How it works:</strong></p><ul><li>Constructs a <strong>POST request</strong> to <a href="http://localhost:8000/v1/chat/completions.">http://localhost:8000/v1/chat/completions.</a></li><li>Sends a <strong>JSON payload</strong> containing:</li><li>The model name.</li><li>The user’s question (as a message).</li><li>Waits for the response and returns it as <strong>JSON</strong>.</li></ul><p><strong>Key Features:</strong></p><ul><li><strong>Blocking call</strong> (waits until the full response is generated).</li><li>Raises an <strong>exception</strong> if the request fails.</li></ul><h4>stream_llm_response function</h4><p><strong>Purpose:</strong><br>Streams responses from vLLM instead of waiting for the full output.</p><p><strong>How it works:</strong></p><ul><li>Sends a <strong>POST request</strong> with &quot;stream&quot;: True, enabling <strong>chunked responses</strong>.</li><li>Uses response.iter_lines() to <strong>process response chunks in real-time</strong>.</li><li>Each received chunk is <strong>decoded and yielded</strong> as a stream.</li></ul><p><strong>Key Features:</strong></p><ul><li><strong>Non-blocking streaming</strong> (useful for chatbots &amp; interactive applications).</li><li>Data is returned in small parts, reducing perceived latency.</li></ul><p>And we tested it so it outputted something like this</p><pre>{<br>  &quot;id&quot;: &quot;chatcmpl-680bc07cd6de42e7a00a50dfbd99e833&quot;,<br>  &quot;object&quot;: &quot;chat.completion&quot;,<br>  &quot;created&quot;: 1738129381,<br>  &quot;model&quot;: &quot;deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B&quot;,<br>  &quot;choices&quot;: [<br>    {<br>      &quot;index&quot;: 0,<br>      &quot;message&quot;: {<br>        &quot;role&quot;: &quot;assistant&quot;,<br>        &quot;content&quot;: &quot;&lt;think&gt;\nOkay, so I&#39;m trying to find out what the capital of France is. Hmm, I remember hearing a few cities named after the myths or something. Let me think. I think Neuch portfolio is where the comma was named. Yeah, that&#39;s right, until sometimes they changed it, but I think it&#39;s still there now. Then there&#39;s Charles-de-Lorraine. I&#39;ve seen that name written before in various contexts, maybe managers or something. And then I think there&#39;s Saint Mal\u25e6e as a significant city in France. Wait, I&#39;m a bit confused about the last one. Is that the capital or somewhere else? I think the capital blew my mind once, and I still don&#39;t recall it. Let me think of the names that come to mind. Maybe Paris? But is there something else? I&#39;ve heard about places likequalification, Guiness, and Agoura also named after mythological figures, but are they capitals? I don&#39;t think so. So among the prominent ones, maybe Neuch portfolio, Charles-de-Lorraine, and Saint Mal\u25e6e are the names intended for the capital, but I&#39;m unsure which one it is. Wait, I think I might have confused some of them. Let me try to look up the actual capital. The capital of France is a city in the eastern department of\u5c55\u51fa. Oh, right, there&#39;s a special place called Place de la Confluense. Maybe that&#39;s where the capital is. So I think the capital is Place de la Confluense, not the city name. So the capital isn&#39;t the town; it&#39;s quite a vein-shaped area. But I&#39;m a bit confused because some people might refer to just the town as the capital, but in reality, it&#39;s a larger area. So to answer the question, the capital of France is Place de la Confluense, and its formal name is la Confluense. I&#39;m not entirely certain if there are any other significant cities or names, but from what I know, the others I listed might be historical places but not exactly capitals. Maybe the\u6bebot\u00e9 family name is still sometimes used for the capital, but I think it&#39;s not the actual name. So putting it all together, the capital is Place de la Confluense, and the correct name is \&quot;la Confluense.\&quot; The other names like Neuch portfolio are places, not capitals. So, overall, my answer would be the capital is la Confluense named at Place de la Confluense.\n&lt;/think&gt;\n\nThe capital of France is called Place de la Confluense. Its official name is \&quot;la Confluense.\&quot;&quot;,<br>        &quot;tool_calls&quot;: []<br>      },<br>      &quot;logprobs&quot;: null,<br>      &quot;finish_reason&quot;: &quot;stop&quot;,<br>      &quot;stop_reason&quot;: null<br>    }<br>  ],<br>  &quot;usage&quot;: {<br>    &quot;prompt_tokens&quot;: 10,<br>    &quot;total_tokens&quot;: 550,<br>    &quot;completion_tokens&quot;: 540,<br>    &quot;prompt_tokens_details&quot;: null<br>  },<br>  &quot;prompt_logprobs&quot;: null<br>}</pre><h4>API Pathing</h4><pre>from fastapi import FastAPI<br>from fastapi.middleware.cors import CORSMiddleware<br>import nest_asyncio<br>from pyngrok import ngrok<br>import uvicorn<br>import getpass<br><br>from pyngrok import ngrok, conf<br><br>app = FastAPI()<br><br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&#39;*&#39;],<br>    allow_credentials=True,<br>    allow_methods=[&#39;*&#39;],<br>    allow_headers=[&#39;*&#39;],<br>)<br><br>@app.get(&#39;/&#39;)<br>async def root():<br>    return {&#39;hello&#39;: &#39;world&#39;}<br>@app.post(&quot;/api/v1/generate-response&quot;)<br>def generate_response(request: QuestionRequest):<br>    &quot;&quot;&quot;<br>    API endpoint to generate a response from the model.<br>    &quot;&quot;&quot;<br>    try:<br>        response = ask_model(request.question, request.model)<br>        return {&quot;response&quot;: response}<br>    except Exception as e:<br>        raise HTTPException(status_code=500, detail=str(e))<br><br>@app.post(&quot;/api/v1/generate-response-stream&quot;)<br>def stream_response(request:QuestionRequest):<br>  try:<br>    response = stream_llm_response(request.question, request.model)<br>    return StreamingResponse(response, media_type=&quot;text/event-stream&quot;)<br>  except Exception as e:<br>    raise HTTPException(status_code=500, detail=str(e))</pre><p>Okay now we create the API pathing for each function that we create, each API would use different function is it going to use stream approach or just generate response but blocking. Here we just need some fast thing, so we are going to allow everything. If error happened we just return it internal server error and detail it the error.</p><h4>ngrok -&gt; public test</h4><pre>! ngrok config add-authtoken ${your-ngrok-token}</pre><p>now we are going to add config token and just copy paste your token from ngork dashboard <a href="https://dashboard.ngrok.com/login">here</a>.</p><h4>Expose it</h4><p>After that we expose it.</p><pre>port = 8081<br># Open a ngrok tunnel to the HTTP server<br>public_url = ngrok.connect(port).public_url<br>print(f&quot; * ngrok tunnel \&quot;{public_url}\&quot; -&gt; \&quot;http://127.0.0.1:{port}\&quot;&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sRbk2LxfNDnIPlvI2xKK3w.png" /></figure><p>We got return exposed tunnel to hit using curl or postman.</p><pre>nest_asyncio.apply()<br>uvicorn.run(app, port=port)</pre><p>And end it with this, to run the service, and whoalaaa it run perfectly…. I think.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFLOiVfmwtMH-pPpB2hnAQ.png" /></figure><p>now you could hit it something like this.</p><pre>curl --location &#39;https://6ee6-34-125-245-24.ngrok-free.app/api/v1/generate-response-stream&#39; \<br>--header &#39;Content-Type: application/json&#39; \<br>--data &#39;{<br>    &quot;question&quot;: &quot;where is paris?&quot;,<br>    &quot;model&quot;: &quot;deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B&quot;<br>}&#39;</pre><p>and got a response more like this if you opted for each token stream response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OKtkCqdLe1vzDfTZT-B-PA.png" /><figcaption>response each token via stream response</figcaption></figure><p>And gaaaly it’s pretty good, the response it’s kinda fast…… I think but the output answer it’s pretty good (if you want a more concise answer, like about code and less about creativity). But this is pretty good for an open-source model after Llama by Facebook.</p><p>Full Code could be accessed here</p><p><a href="https://github.com/naufalhakim23/deepseek-r1-playground/blob/main/deepseek_r1_distill_qwen_fast_api.ipynb">https://github.com/naufalhakim23/deepseek-r1-playground/blob/main/deepseek_r1_distill_qwen_fast_api.ipynb</a></p><h4>End it.</h4><p>After all of this, I would recommend you guys…. If you have the money buy the GPU if you want to run it locally but you will need an overhead of a pretty good GPU and electricity bill, but you have the option of you own of your data. Use chat.deepseek.com you could use this if you want to use FAAASSTTTT deepseek llm (with 671B params), but your data isn’t only yours like any other platform like Claude and OpenAi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gps9qAkolTGI7o99jTlz9w.png" /></figure><p>I’d love to hear your thoughts on how to test vllm in google colab! Let me know in the comments, or feel free to share your optimizations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4fe682b8665" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple Go HTTP Requests “GET” and Response Handling]]></title>
            <link>https://medium.com/@hakimnaufal/simple-go-http-requests-get-and-response-handling-b6fd83d62a5e?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6fd83d62a5e</guid>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 08:21:32 GMT</pubDate>
            <atom:updated>2024-07-27T08:21:32.576Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello, it’s been a while since I wrote something so bear with me on this, today I want to show you the minimum of how I handled request http and response handling in Go this past couple of years.</p><p>Okay, why are we talking about this? Because some fancy tooling such as Resty will make you don’t know anything…. nahhh just kidding…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*NFRuPn08-oDC31DlmQUQ2Q.png" /></figure><p>Ahahahahah~~~ because if you can master the simple one, you could do everything.</p><p>Anyway let’s get into it.</p><p>In Go, we’re always using net/http as a package for requests like this</p><pre>func main() {<br>    // Create a new HTTP client<br>    client := &amp;http.Client{<br>        Timeout: time.Second * 10, // Timeout each requests<br>    }<br>    // Example usage<br>    url := &quot;https://example.com/api&quot;<br>    method := &quot;POST&quot;<br>    payload := strings.NewReader(`{&quot;key1&quot;:&quot;value1&quot;, &quot;key2&quot;:&quot;value2&quot;}`)<br><br>    req, err := http.NewRequest(method, url, payload)<br>    if err != nil {<br>        fmt.Println(&quot;Error creating request:&quot;, err)<br>        return<br>    }<br>    // Set headers<br>    req.Header.Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br>    req.Header.Add(&quot;Authorization&quot;, &quot;Bearer YOUR_TOKEN&quot;)<br><br>    // Execute the request using the custom HTTP client<br>    resp, err := client.Do(req)<br>    if err != nil {<br>        fmt.Println(&quot;Error making request:&quot;, err)<br>        return<br>    }<br>    defer resp.Body.Close()<br><br>    // Read and print response<br>    body, err := io.ReadAll(resp.Body)<br>    if err != nil {<br>        fmt.Println(&quot;Error reading response body:&quot;, err)<br>        return<br>    }<br>    fmt.Println(string(body))<br>}</pre><p>This is the simplest way you could do on hitting the API and getting the response but how can I handle the response properly?</p><p>If you’re using Structs so it got marshaled into it and use the data then you might wanna do this.</p><pre>package model<br><br>type PokemonDetails struct {<br> Abilities      []Abilities `json:&quot;abilities&quot;`<br> BaseExperience int         `json:&quot;base_experience&quot;`<br> Weight         int         `json:&quot;weight&quot;`<br>}<br>type Ability struct {<br> Name string `json:&quot;name&quot;`<br> URL  string `json:&quot;url&quot;`<br>}<br>type Abilities struct {<br> Ability  Ability `json:&quot;ability&quot;`<br> IsHidden bool    `json:&quot;is_hidden&quot;`<br> Slot     int     `json:&quot;slot&quot;`<br>}</pre><pre>package main<br><br>import (<br> &quot;context&quot;<br> &quot;encoding/json&quot;<br> &quot;fmt&quot;<br> &quot;io&quot;<br> &quot;net/http&quot;<br> &quot;strings&quot;<br><br> &quot;test/model&quot;<br><br> &quot;github.com/sirupsen/logrus&quot;<br>)<br><br>// Create a new HTTP client<br>var client = &amp;http.Client{}<br><br>func requestNew(ctx context.Context, httpMethod, uri string, body io.Reader) (*http.Request, error) {<br> req, err := http.NewRequestWithContext(ctx, httpMethod, uri, body)<br> if err != nil {<br>  fmt.Println(&quot;Error creating request:&quot;, err)<br>  return req, err<br> }<br><br> // Set headers<br> req.Header.Add(&quot;Content-Type&quot;, &quot;application/json&quot;)<br><br> return req, nil<br>}<br><br>func execRequest(request *http.Request, bodyInterface interface{}) (status int, err error) {<br> // Execute the request using the custom HTTP client<br> resp, err := client.Do(request)<br> if err != nil {<br>  fmt.Println(&quot;Error making request:&quot;, err)<br>  return<br> }<br> status = resp.StatusCode<br> defer resp.Body.Close()<br><br> // Check for a successful status code<br> if resp.StatusCode != http.StatusOK {<br>  return resp.StatusCode, fmt.Errorf(&quot;error: received status code %d&quot;, resp.StatusCode)<br> }<br><br> // Decode the JSON response using json.NewDecoder<br> decoder := json.NewDecoder(resp.Body)<br> if bodyInterface != nil {<br>  if err = decoder.Decode(bodyInterface); err != nil {<br>   return status, fmt.Errorf(&quot;error decoding response body: %v&quot;, err)<br>  }<br> }<br><br> return<br>}<br><br>func GetPokemonDetails(ctx context.Context, pokemonName string) (response *model.PokemonDetails, status int, err error) {<br> req, err := requestNew(ctx, http.MethodGet, fmt.Sprintf(&quot;https://pokeapi.co/api/v2/pokemon/%s&quot;, strings.ToLower(pokemonName)), nil)<br> if err != nil {<br>  return response, http.StatusInternalServerError, err<br> }<br><br> status, err = execRequest(req, &amp;response)<br> if err != nil {<br>  return<br> }<br><br> return<br>}<br><br>func main() {<br> ctx := context.Background()<br> resData, status, err := GetPokemonDetails(ctx, &quot;mankeys&quot;)<br> if err != nil {<br>  logrus.Error(err)<br>  return<br> }<br><br> switch status {<br> case http.StatusOK:<br>  jsonjson, _ := json.Marshal(resData)<br>  logrus.Info(string(jsonjson))<br> default:<br>  err = fmt.Errorf(&quot;response api %v&quot;, status)<br>  logrus.Error(err)<br>  return<br> }<br>}</pre><p>by doing this you will retrieve the data pointed to the response struct, the status that will be passed, or even the error that will happen.</p><p>Why the heck we’re using json.NewDecoder???</p><blockquote><strong>Memory Efficiency</strong>: json.NewDecoder is beneficial for large responses because it decodes the JSON data in a streaming manner.</blockquote><p>and whoalaaa it’s all handled, of course it’s the bare minimum, and the response should be</p><pre>INFO[0000] {&quot;abilities&quot;:[{&quot;ability&quot;:{&quot;name&quot;:&quot;vital-spirit&quot;,&quot;url&quot;:&quot;https://pokeapi.co/api/v2/ability/72/&quot;},&quot;is_hidden&quot;:false,&quot;slot&quot;:1},{&quot;ability&quot;:{&quot;name&quot;:&quot;anger-point&quot;,&quot;url&quot;:&quot;https://pokeapi.co/api/v2/ability/83/&quot;},&quot;is_hidden&quot;:false,&quot;slot&quot;:2},{&quot;ability&quot;:{&quot;name&quot;:&quot;defiant&quot;,&quot;url&quot;:&quot;https://pokeapi.co/api/v2/ability/128/&quot;},&quot;is_hidden&quot;:true,&quot;slot&quot;:3}],&quot;base_experience&quot;:61,&quot;weight&quot;:280}</pre><p>Oh yeah, I heard someone say that</p><blockquote>overhandling errors, missing data, or even status is better than less handling, from that you can adjust on whose going to error one by one or the best path on handling everything.</blockquote><p>In this post, we’ve explored how to make HTTP GET requests in Go using the net/http package. We&#39;ve covered how to handle JSON responses, check status codes, and work with headers. With these techniques, you can effectively retrieve and interact with data from APIs in your Go applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6fd83d62a5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing for NextJS with Jest, Testing Library and msw]]></title>
            <link>https://medium.com/@hakimnaufal/unit-testing-for-nextjs-with-jest-testing-library-and-msw-88bee354c86?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/88bee354c86</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[msw]]></category>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 08:33:48 GMT</pubDate>
            <atom:updated>2023-01-06T08:33:48.489Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone it’s been a while since I post this kind of stuff but yeah it’s nice to be able to write agin. Where have I been? yeah I’m Interning at eFishery for the most of my 3 months and this month (January) is the end of the Internship (may I got to be a regular in eFishery).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*F0tltlqiOvcgzGcMzE79uQ.gif" /><figcaption>be with me ofc :)</figcaption></figure><p>Anyway let’s jump into the bussiness What is Unit Testing?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*35EQnC8aZiMUIQ5rMdeK7A.png" /></figure><p>“ Unit testing is an important part of the development process because it helps ensure that individual components of a React application are working as expected. This makes it easier to catch and fix bugs before they become a problem, and it also helps to ensure that changes to one part of the code do not break other parts of the application.<br>Additionally, unit tests can provide a sort of “living documentation” for a project, as they can be used to verify that a component is working as intended and can be relied upon to behave in a certain way. This can be especially useful for larger projects with many different components, as it can help ensure that the different parts of the application are working together correctly.”<br>(Generated by <a href="http://chat.openai.com/">chat.openai.com</a>)</p><p>So it’s pretty much a test for each component mainly UI in this case such as the page itself, components, library even hooks if you want it to do something specific or even that data that you get. Because developer needs to check the performance of each unit and prevent possible problems in advance. The purpose is to validate that each unit of the software code performs as expected.</p><p>Throughout the product development lifecycle, unit tests save your time and money and help make code quality better.</p><p>Soooo without a further a do lets jump in to the code.<br>First thing first we should set up the NextJS, its pretty much using</p><pre>yarn create next-app --typescript</pre><p>After that we added the spices that is jest, msw and @testing-library</p><pre>yarn add --dev jest@27.5.1 msw@0.35.0 @testing-library/react@12.1.3 @testing-library/jest-dom@5.16.2 @testing-library/user-event@14.4.3</pre><p>why am I using msw?? well it’s about the server like behavior that it replicates it’s an mock server that really helped you to test your unit test without consuming real API from live backend, and the behavior is specked as you intended.</p><p>if you want the full tutorial of the msw you should check out <a href="https://www.youtube.com/@jmagrippis"><br>Johnny Magrippis</a> youtube channel it’s really easy to follow</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FeLqrry2ezh8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DeLqrry2ezh8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FeLqrry2ezh8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/91df62c7c1f2af36b6ed72051ec993c8/href">https://medium.com/media/91df62c7c1f2af36b6ed72051ec993c8/href</a></iframe><p>Anyway after that we need to setup the package json first, we need to add</p><pre>    &quot;test&quot;: &quot;jest --watchAll --coverage&quot;,<br>    &quot;test:ci&quot;: &quot;jest --coverage&quot;,<br>    &quot;test:single&quot;: &quot;jest --watch --collectCoverage=false&quot;,</pre><p>this will help us to test the components, if you want to run all of it you just neeed to use yarn test, but if you want to test one component just run yarn test:single ……tsx that easy :)</p><p>we too need to add jest.config.js to our main repo, this will help us to run NextJS jest rust compiler</p><pre>const nextJest = require(&quot;next/jest&quot;);<br>const createJestConfig = nextJest({<br>  dir: &quot;./&quot;,<br>});<br>const customJestConfig = {<br>  moduleDirectories: [&quot;node_modules&quot;, &quot;&lt;rootDir&gt;/&quot;],<br>  testEnvironment: &quot;jest-environment-jsdom&quot;,<br>  setupFilesAfterEnv: [&quot;&lt;rootDir&gt;/jest.setup.js&quot;],<br>  testRegex: &quot;(/__tests__/.*|(\\.|/)(test|spec))\\.(jsx?|tsx?)$&quot;,<br>  testPathIgnorePatterns: [&quot;&lt;rootDir&gt;/.next/&quot;, &quot;&lt;rootDir&gt;/node_modules/&quot;, &quot;&lt;rootDir&gt;/cypress/&quot;],<br>};<br>module.exports = createJestConfig(customJestConfig);</pre><p>add more spice into the tsconfig.json into compiler option</p><pre>    &quot;target&quot;: &quot;es5&quot;,<br>    &quot;lib&quot;: [&quot;dom&quot;, &quot;dom.iterable&quot;, &quot;esnext&quot;],<br>    &quot;allowJs&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;strict&quot;: true,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;noEmit&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;module&quot;: &quot;esnext&quot;,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;isolatedModules&quot;: true,<br>    &quot;jsx&quot;: &quot;preserve&quot;,<br>    &quot;incremental&quot;: true,<br>    &quot;downlevelIteration&quot;: true,<br>    &quot;types&quot;: [&quot;jest&quot;, &quot;node&quot;, &quot;@testing-library/jest-dom&quot;]</pre><p>and before you mock your server and handler you should create jest.setup.js that will run first and foremost before running the test</p><pre>import &#39;@testing-library/jest-dom&#39;;<br>import { server } from &#39;./mocks/server&#39;;<br>beforeAll(() =&gt; server.listen());<br>afterEach(() =&gt; server.resetHandlers());<br>afterAll(() =&gt; server.close());</pre><p>okay now the fun part mocking the backend, in the folder you should have a folder for mocks itself (because it would be organized) like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*w4oa6XfcN4J-RZpWGmJAug.png" /><figcaption>whoaaaa prettyy right/??</figcaption></figure><p>in the server is just simple, it only has 3 line of code</p><pre>import { setupServer } from &#39;msw/node&#39;<br>import { handlers } from &#39;./handlers&#39;<br><br>export const server = setupServer(...handlers)</pre><p>but here in the api kinda get messy, because it replicate what we want to receive sooo we need to do api first and the handlers.</p><p>after that shebang we got ourself a mocked server response.</p><p>the test itself would be a breeze. lets go on an example so we have a components lets said a day timer that is inside a &lt;Box&gt; div (ok i’m using chakra) we only need to do and if you’re using some render hooks inside of it you could test it too.</p><pre>import { render, screen, act } from &#39;@testing-library/react&#39;<br>import DeadlineDetailSection from &#39;../DeadlineDetailSection.component&#39;<br>import dayjs from &#39;dayjs&#39;<br><br>describe(&#39;DeadlineDetailSection working with time ticking &#39;, () =&gt; {<br>  it(&#39;should render payment DeadlineDetailSection components with working hooks&#39;, async () =&gt; {<br>    const targetDate = &#39;2100-02-01T11:23:00+07:00&#39;<br>    const target = dayjs(targetDate).valueOf()<br>    const currentTimerCount = target - new Date().getTime()<br>    const remainDays = String(Math.floor(currentTimerCount / (1000 * 60 * 60 * 24))) || &#39;0&#39;<br>    render(&lt;PaymentDeadlineSection deadline={targetDate} /&gt;)<br>      await act(async () =&gt; {<br>        await new Promise((resolve) =&gt; setTimeout(resolve, 1000))<br>        expect(screen.getByText(&#39;Batas Pembayaran&#39;)).toBeInTheDocument()<br>        expect(screen.getByText(dayjs(targetDate).format(&#39;dddd, DD MMMM YYYY&#39;))).toBeInTheDocument()<br>        expect(screen.getByText(`${remainDays} Hari`)).toBeInTheDocument()<br>      })<br>  }),<br>  it(&#39;should render payment deadline section components with working hooks, but input deadline is already passed&#39;, async () =&gt; {<br>    render(&lt;PaymentDeadlineSection deadline={&#39;2013-10-17T11:23:00+07:00&#39;} /&gt;)<br>    await act(async () =&gt; {<br>      await new Promise((resolve) =&gt; setTimeout(resolve, 1000))<br>      expect(screen.getByText(&#39;Batas Pembayaran&#39;)).toBeInTheDocument()<br>      expect(screen.getByText(&#39;00:00:00&#39;)).toBeInTheDocument()<br>    })<br>  })<br>})</pre><p>aaaannnddd whoaaalaaa it would be 100% right now, I know it’s not effective because it isn’t mocked using jest.mock, but it’s an reactive approach to the case and it should have 100% coverage of it.</p><p>And using API mocks have a higher chance to have a bigger coverage too. Probably that is it for today it’s short thank you for hearing my rant have a good day y’all. oh yea I now will write again because I forgot to write like every other day :)))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*9DXlKkNmm_M5xwZA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88bee354c86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Final Project Presentation and Closing if eFishery Academy]]></title>
            <link>https://medium.com/@hakimnaufal/final-project-presentation-and-closing-if-efishery-academy-686c38b5cc6c?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/686c38b5cc6c</guid>
            <category><![CDATA[warehouse-management]]></category>
            <category><![CDATA[efishery-academy]]></category>
            <category><![CDATA[efishery]]></category>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Sat, 08 Oct 2022 12:10:12 GMT</pubDate>
            <atom:updated>2022-10-08T12:10:12.864Z</atom:updated>
            <content:encoded><![CDATA[<p>After two weeks of training and learning everything there is for basic backend with Golang from how to make RFC to CRUD API with Clean Architecture to docker file and composed with postgresql. It’s really is awesome this past three weeks (2 week of training and 1 week of final project). I will only talked about the day we presentation from 11 people, only 6 of us there to talked about our presentation and product. Most of us chose the e-commerce or Order Management System but me trying to do some out of the box theme that is Warehouse Management System without detailed specification so… pretty much I tried to talked this one. Even though it’s only one week of preparation I managed to make it and tried to maintained the clean architecture to dockerized and composed with postgresql.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*KehcTjKtjmCJYE8l.gif" /><figcaption>me trying to finish all the stuff we need to presentate</figcaption></figure><p>It was really hard for me (because sometimes the documentation for go stuff isn’t comparable than JS node) so yeah I tried my best. If you want to see my approach of WMS (Warehouse Management System) you could visit my Github here</p><p><a href="https://github.com/naufalhakim23/naufalhakim-efishery-academy/tree/main/9.%20Final%20Project%20-%20Warehouse%20Management%20System">naufalhakim-efishery-academy/9. Final Project - Warehouse Management System at main · naufalhakim23/naufalhakim-efishery-academy</a></p><p>Even though there is some bugs and kink in the program, I think I could do it better than now after seeing my friends approach on OMS. It was an awesome day to be part of it even though it was nervous af but in the end we all tried our best and felt relieved and now is just the waiting game who got the job and who doesn’t. Oh yeah our projects was reviewed by seniors from tech data to product manager it was nerve wrecking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*VNMLaF9BAXT2KkJrO8Zddw.jpeg" /></figure><p>After presentation we were greeted by mas <a href="https://medium.com/u/267481a159ca">Puja Pramudya</a> as the Head of Engineering and Academy in eFishery and thank us for finishing our study there for two weeks and the final project and more info about other department like tech data to product manager that was in the middle of new product and was ended with mas Imam as one of the VP of Product Engineering giving us some insight when he was a student. “It’s not about always a straight A’s If you can go for it but if you are tired you could rest a bit ”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eU8MvQQqoRxX2Zk-quBtZQ.jpeg" /></figure><p>And was ended with a little bit of PIZZA PARTYYYY EYYYYYYY really appreciate it for the three weeks with you all eFisherian, thank you to my colleague, friends, mentor and all seniors that helped me grow more and as always mari #TumbuhBersama.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TviOVXNWnpikIvGMKGlJQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=686c38b5cc6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Compose Day10 eFishery Academy]]></title>
            <link>https://medium.com/@hakimnaufal/docker-compose-day10-efishery-academy-29d65c13172a?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/29d65c13172a</guid>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[efishery-academy]]></category>
            <category><![CDATA[efishery]]></category>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 23:44:34 GMT</pubDate>
            <atom:updated>2022-09-30T23:44:34.356Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s already the end of the 2 weeks in eFishery Academy… Dang it’s been two unforgettable weeks I’ve ever been. Okay now let’s get back to the material for today it’s Docker Compose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Tzu4hWtFcPr8Pp4W.gif" /></figure><p>Before this article I already write a little bit about docker but now we’re going to deploy with docker compose but what is docker compose? Docker Compose “is a <strong>tool that was developed to help define and share multi-container applications</strong>. With Compose, we can create a YAML file to define the services and with a single command, can spin everything up or tear it all down. It can handle multiple containers simultaneously in the production, staging, development, testing, and CI environment. Therefore, use Docker Compose to manage the whole <a href="https://phoenixnap.co/m/blog/software-development-life-cycle">software development lifecycle (SDLC)</a>.” It’s pretty much orchestrate everything for deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/0*s97aw_gjpQWm3jXP.png" /></figure><p>This tool can become very powerful and allow you to deploy applications with complex architectures very quickly. I will give you a concrete case study that will prove that you need it</p><p>.You can combine many Docker containers into one, this would make your life easier to manage every container that we want to deploy. If you made it one by one it would take a loooonnnggg ffreakin time like if you need 3 services 1 for database, 1 for app (processing in the backend), and one for web you would make it 3 different containers and deploy it one by one. But if you use docker compose you combine 3 of the docker containers and create the service sequentially like you want it and deployed it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*1WLKSIiRpk7OHjGe.png" /></figure><h3><strong>Docker Compose Use Case:</strong></h3><ul><li><strong>Automated testing environments</strong>. Compose supports <a href="https://phoenixnap.com/blog/best-automation-testing-tools">automated testing</a>, which is an essential part of CI/CD as it can easily create and destroy the required testing environment. Developers can define and configure the environment needed for running automated end-to-end testing using the appropriate Docker Compose file.</li><li><strong>Single host deployments</strong>. In Docker Compose, containers are designed to run on a single host as they have traditionally been focused on development and testing workflows.</li><li><strong>Development Environments</strong>. Compose is a fast and simple way of starting projects as it can quickly spin up new isolated development environments. The software documents and configures all the application’s service dependencies (including <a href="https://phoenixnap.com/kb/what-is-a-database">databases</a>, caches, web service APIs, etc.). It allows you to create and start one or multiple containers for each dependency using a single command.</li></ul><h3>Benefits of Using Docker Compose</h3><ul><li><strong>Fast and simple configuration.</strong> Thanks to YAML scripts and environment variables, you can easily configure or modify application services.</li><li><strong>Secure</strong> <strong>internal communication.</strong> Compose creates a network for all the services to share. This adds an extra security layer for the app since the services cannot be accessed externally.</li><li><strong>Portability and CI/CD support.</strong> Since all the services are defined inside the docker-compose file, developers can easily access and share the entire configuration. By pulling the YAML file and <a href="https://phoenixnap.com/glossary/what-is-source-code">source code</a>, they can launch the environment in a matter of minutes. This contributes to setting up and enabling an efficient <a href="https://phoenixnap.com/blog/what-is-ci-cd">CI/CD</a> pipeline.</li><li><strong>Efficient use of resources.</strong> Docker Compose allows you to host multiple isolated environments on one host. Running everything on a single piece of hardware lets you save a lot of resources. Its features that enable it to cache a configuration and re-use existing containers also contribute to resource efficiency.</li></ul><p>The full example guide for how to use docker compose are in freeCodeCamp (it’s pretty much the same like in the eFishery Academy): <a href="https://www.freecodecamp.org/news/a-beginners-guide-to-docker-how-to-create-a-client-server-side-with-docker-compose-12c8cf0ae0aa/">https://www.freecodecamp.org/news/a-beginners-guide-to-docker-how-to-create-a-client-server-side-with-docker-compose-12c8cf0ae0aa/</a></p><p>Okay for just tldr eFishery don’t use Docker Compose but nomad as their orchestrator but using Docker Compose we can learn how it works because the principles between every orchestrator is the same such as Nomad and Kubernates.</p><p>And with this come to an end of the two weeks journey in eFishery Academy right now I’m in the process to finish my final project and determined if I could go on to the next stage that is internship or not (is this sentence is alright? like is there an error with my brain?). Now I need y’all help to pray may god bless me and all of my colleague go on to the next stage. Amen.</p><p>Thank you for you all participating on reading this such very few article for 2 weeks I talked about ranting to stuff that I’ve never know like Go and even what is nomad it’s such a fun journey to met a new friends, new mentor, new environment it is and will always be awesome to be part of eFishery Academy. I hope y’all get inspired or even register when there are another Aqua Developer in eFishery Academy. This medium still gonna be around but not daily updates, and I will try to write more in the coming future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*O4XIRBtJpw-Nw01z.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29d65c13172a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud Native and Infrastructure in eFishery Day-9 at eFishery Academy]]></title>
            <link>https://medium.com/@hakimnaufal/cloud-native-and-infrastructure-in-efishery-day-9-at-efishery-academy-626e81cf04a6?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/626e81cf04a6</guid>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[efishery-academy]]></category>
            <category><![CDATA[tech-stack]]></category>
            <category><![CDATA[efishery]]></category>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Fri, 30 Sep 2022 02:22:28 GMT</pubDate>
            <atom:updated>2022-09-30T02:22:28.433Z</atom:updated>
            <content:encoded><![CDATA[<p>Good day y’all another day, another things to learn so It’s Cloud Native time with SRE Tech Lead in eFishery Mr Wahyu Anggana. First what is Cloud Native? Cloud Native is “<em>A new computing paradigm that is optimized for modern distributed systems environments, capable of scaling to tens of thousands of self-healing multi-tenant nodes” </em>It describes a set of principles and practices that developers follow to construct applications optimized for modern cloud environments. Special attention is given to portability across environments and declarative automation. In every tech company have their tech stack (like what are they using to build all of their tech) eFishery use some too (ofc it’s tech company dumbo).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tg8wVf94Yk2hvrVo-A6AXQ.png" /><figcaption>eFishery Tech Stack</figcaption></figure><p>The differences that in their tech stack is the use of nomad for deployment and release because not many tech company use nomad but eFishery use nomad because of the use what you need not like Kubernetes that you have all of it and Kubernetes have their own vault for each node you can’t use one vault and share it between 2 or even infinite amount of secret code from one source vault.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LJto2HD_2f34G8F9j9OJLw.png" /><figcaption>Kubernetes vs nomad architecture</figcaption></figure><p>It has many stuff you need to go through or have to make we will start from:</p><ul><li>Codebase : A single code base for each microservice, stored in its own repository. Tracked with version control, it can deploy to multiple environments (QA, Staging, Production).</li><li>Dependencies : Each microservice isolates and packages its own dependencies, embracing changes without impacting the entire system.</li><li>Configuration : Configuration information is moved out of the microservice and externalized through a configuration management tool outside of the code. The same deployment can propagate across environments with the correct configuration applied.</li><li>Backing Service : Ancillary resources (data stores, caches, message brokers) should be exposed via an addressable URL. Doing so decouples the resource from the application, enabling it to be interchangeable.</li><li>Build/Run/Release : Each release must enforce a strict separation across the build, release, and run stages. Each should be tagged with a unique ID and support the ability to roll back. Modern CI/CD systems help fulfill this principle.</li><li>Process : Each microservice should execute in its own process, isolated from other running services. Externalize required state to a backing service such as a distributed cache or data store.</li><li>Port Binding : Each microservice should be self-contained with its interfaces and functionality exposed on its own port. Doing so provides isolation from other microservices.</li><li>Concurrency : When capacity needs to increase, scale out services horizontally across multiple identical processes (copies) as opposed to scaling-up a single large instance on the most powerful machine available. Develop the application to be concurrent making scaling out in cloud environments seamless.</li><li>Dev/Prod Parity : Keep environments across the application lifecycle as similar as possible, avoiding costly shortcuts. Here, the adoption of containers can greatly contribute by promoting the same execution environment.</li><li>Logging : Treat logs generated by microservices as event streams. Process them with an event aggregator. Propagate log data to data-mining/log management tools like Azure Monitor or Splunk and eventually to long-term archival.</li><li>Admin Process : Run administrative/management tasks, such as data cleanup or computing analytics, as one-off processes. Use independent tools to invoke these tasks from the production environment, but separately from the application.</li></ul><p>It’s pretty mouthful and steps you need to go through but it will be worth it if you already have the basis covered after this all got covered this all stuff would make your life easier as Infra peeps but let’s go back to Containers before we could even go through that all.</p><p>What is Containers? it’s an abstraction at the app layer that packages the code and the dependencies together and the tool that can helped us is Docker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rbbB9zyLxWjYG4fP" /></figure><p>For more easier to explain what is docker we could quotes from <a href="https://medium.com/u/55d69ffd1589">Ilia Mikhailov</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*SzAsX_QccXTfKh6-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*jnZvAsO3FGorDTAK" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*bkwjLqG6VTPM1ftm" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*BAqirkOxgsHhEdvZ" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/0*UJcLlaTzBY0foYG4" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*sZMTI1-H-ZYqtoJ2" /></figure><p>Thank you <a href="https://medium.com/u/55d69ffd1589">Ilia Mikhailov</a> for the easy explanation even me that new into cloud native understand it really nicely. Okay in the class we got instructed how to make docker file, how to interact with it, how to push it to docker hub, etc. It’s easy :) anyway lets go to eFishery deployment process</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zT3MCYUXufjPB_T9KLLQxQ.png" /></figure><p>Ofc eFishery have their own software to integrate it all and it called CiBi a custom CI/CD to assist all of the deployment process. With hard work for 2 years they now have a pretty solid automated integration through all the process. There are moooreee stuff that I want to share but don’t really know if it’s okay to share tho (I don’t signed any NDA but still it’s corporate secrets). Their infrastructure already deliver more than hundreds more deployment and etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ts1YbayE7oL64_hqMV152w.png" /></figure><p>with all of this you can’t even deploy manually and even tried do 200+ deployment to different app they have (microacrhitecture style). It’s pretty big for me to look at these number while I was just deploying one or two finished project for each 6 months ( it’s my personal project okay )… Yikesssssssss</p><p>This is why I believe in their tech from hardware the eFeeder to software. That is it for today time to sign off for the day have a good day everyone :))))))</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/0*13eLfX7LjVEEhdTB.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=626e81cf04a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OneFish Design System at eFishery Day-8]]></title>
            <link>https://medium.com/@hakimnaufal/onefish-design-system-at-efishery-day-8-45ef0be24703?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/45ef0be24703</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[efishery-academy]]></category>
            <category><![CDATA[efishery]]></category>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Thu, 29 Sep 2022 02:08:12 GMT</pubDate>
            <atom:updated>2022-09-29T02:08:12.811Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi there, it’s already the eight days into the academy but I hope I passed the exam and got the internship here. Now we are talking about <strong>Design System, </strong>almost all of the big tech company or even any company they all have a design that flows with their logo, color, typography and even animations of the button or graphical stuff. It’s all about the User Interface and User Experience. “It’s a design system is a complete set of standards intended to manage design at scale using reusable components and patterns.” Why do we need design system? this is a few reasons you need to implement design system:</p><ul><li>Design (and development) work can be created and replicated quickly and at scale.</li><li>It alleviates strain on design resources to focus on larger, more complex problems.</li><li>It creates a unified language within and between crossfunctional teams.</li><li>It creates visual consistency across products, channels, and (potentially siloed) departments.</li><li>It can serve as an educational tool and reference for junior-level designers and content contributors.</li></ul><p>Let’s go with an example or two.</p><ol><li><a href="https://gojek.design/">Gojek</a></li></ol><p>We all know what is Gojek ( people in Indonesia ) before they implement it into the app their UI/UX designer research on color even animation that easy to see and really different than any other app because it would stick to their user brains. Like once Google research about the best blue that engaged people to have more traffic to buy or do transaction (allegedly true).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibj8ZPOQPkPG6quSh5PCMw.png" /><figcaption>Gojek Design System</figcaption></figure><p>But we now know what is the identity of Gojek, why the swirl in the logo, why that color are implemented, why their logos are like that.</p><p>Now we are going into eFishery OneFish Design System</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fv2cRncSjmZLq4njrkycw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68c4RIe3qbg6GAWunItn9A.png" /><figcaption>Shades of color eFishery use</figcaption></figure><p>eFishery used 8 different shades of green to engaged users, in color psychology, colors made up of long wavelengths are considered “arousing or warm,” whereas colors such as green that have shorter wavelengths are “relaxing or cool.” Whereas our eyes must adjust to see colors with longer wavelengths, they don’t need to adjust at all to see cool colors other than that their principles are:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*-Xrw3OOWLzr506b7fTcDFg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9LsdcbrsoVo7QejWO2iA_g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cPp9-0s6J0bswG-3pvxpQ.png" /></figure><p>From the OneFish design we have a coherent and one flow from website to three different apps while having the same consistency in every webapp or mobile apps. In the end it helps the developer to have consistent on every design and developer don’t really need to tweak more than it should (such as making new product logos and etc).</p><p>That is it for today it’s short but it help us as developer to not think about designing from 0 to 100 on their own, thank you for hearing my rant have a good day y’all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*RKQWTIOhvQfLEXX0.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45ef0be24703" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean Architecture for Golang Day7-eFishery Academy]]></title>
            <link>https://medium.com/@hakimnaufal/clean-architecture-for-golang-day7-efishery-academy-5f73a4fa4d73?source=rss-352868fa89ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f73a4fa4d73</guid>
            <category><![CDATA[efishery]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[efishery-academy]]></category>
            <dc:creator><![CDATA[Naufal Al Hakim]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 07:51:55 GMT</pubDate>
            <atom:updated>2022-09-28T07:51:55.356Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello y’all how’s life…. After advance Go and API you will need to write code that is clean, arranged, and easy to read that’s why you need to learn how to write a clean code. <strong>Clean architecture</strong> itself is <strong>a software design philosophy that separates the elements of a design into ring levels</strong>. An important goal of clean architecture is to provide developers with a way to organize code in such a way that it encapsulates the business logic but keeps it separate from the delivery mechanism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZwWbjUVOe53WJZj9.jpg" /></figure><p>It should be noted every company have a different approach at how to managed a clean architecture for codes and this is what I learn (as it’s simple as it gets).</p><h3>My (our) approach of clean code in eFishery Academy</h3><p>The approach is to write and separate routes, handler, repository(connection to database using ORM or not), config (for database or password hashing), entity, and the last one is usecase (what is our input and output).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*vZ1qZ8ZTCXP4h1jIRJxGUA.png" /></figure><p>Each folder has it own purpose to start it all up is config, it’s a configuration that we use such as postgresql (database) or our hashing function or etc is all saved into this folder. Entity is pretty much a structure of input data, output data for client or even error handling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KrF4Ks3n1lHUFO_oCAKU1A.png" /></figure><p>Handler used for how we handle the input and output data from sending and receiving data to http code such as 200, 300, 400 and even 500 error code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*aW5PdRs2xRy_V9Nent_v1A.png" /></figure><p>Repository pretty much where the input code interact to the database using ORM or plain SQL how are we going to input is it Creating new user, Find the user or even Removing the user from database table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/913/1*TueuBgXjr1ZHtUUqFErizw.png" /></figure><p>Usecase is input and output of the data what are the data we sending to the client what are we need from the client to give out the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kt7Uk9XO1rgDDOFCdAurtQ.png" /></figure><p>and the last one is….. routes, this is the most straight forward it’s where we save the routes to access the data is it POST, PUT, PATCH, DELETE or etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/1*AwIsbo_8HR6tGEVrv2drSw.png" /></figure><p>It’s pretty clean and not cluttery code as I do myself, but it’s easier to locate where it is error (if you wrote the wrong code from repository it’s pretty much you made errors in all folder except entity) it’s interconnected while it’s in different folders it’s easier to know where you are. Oh yeah if you are using WSL and have a postgresql in your windows, Good Luck finding a way to connect your postgresql to WSL (even I don’t know how please if you know how just comment down here :) ). Anyway if you want to read my code I hope it isn’t cluttery you can find me up in github.</p><p><a href="https://github.com/naufalhakim23/naufalhakim-efishery-academy/tree/exercise-clean-architecture/7.1.%20Exercise%20Clean%20Architecture">naufalhakim-efishery-academy/7.1. Exercise Clean Architecture at exercise-clean-architecture · naufalhakim23/naufalhakim-efishery-academy</a></p><p>It’s a pretty short one but if you read and re-write the code it’s pretty hard for me because I’ve never write Golang with clean architecture at all (because I mainly wrote JS and Python(Jupyter Notebook)). That’s all folks for today.</p><p>BYEEEEEEEEEEEE~~~~~~~~~~</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*1SxtqFmExPTFQVIO.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f73a4fa4d73" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>