<?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 Nipuna Madhushan on Medium]]></title>
        <description><![CDATA[Stories by Nipuna Madhushan on Medium]]></description>
        <link>https://medium.com/@nipunamadhushan96?source=rss-b7586b019f1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vL3Cy7q5pTQ-cRZvgX8v5w.jpeg</url>
            <title>Stories by Nipuna Madhushan on Medium</title>
            <link>https://medium.com/@nipunamadhushan96?source=rss-b7586b019f1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:57:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nipunamadhushan96/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[Building an Observable Microservices Platform on Amazon EKS with Best Practices]]></title>
            <link>https://nipunamadhushan96.medium.com/building-an-observable-microservices-platform-on-amazon-eks-with-best-practices-a91eea81e998?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a91eea81e998</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[opentelemetry]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Sat, 26 Sep 2026 20:47:24 GMT</pubDate>
            <atom:updated>2026-09-26T20:50:07.897Z</atom:updated>
            <content:encoded><![CDATA[<p><em>*Security, observability, scaling, delivery and operations: the practices that matter, applied to a real platform.*</em></p><p>I built and ran a microservices platform on Amazon EKS, and used it to apply the best practices I’d recommend to any team running on Kubernetes. This article covers the practices that mattered most and the incidents that showed why.</p><p>To keep this article short, I refer to the source code in my GitHub repository, <a href="https://github.com/NipunaMadhushan/new-event-cloud-service"><strong>NipunaMadhushan/new-event-cloud-service</strong></a>, instead of including all of it here. Only the most important snippets appear in the article; the full files are linked where they’re relevant.</p><h3><strong>The Platform</strong></h3><p>An events website where visitors browse events and register for tickets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rc8y6qUIEggHBzHEkdO4iw.png" /><figcaption>Solution Architecture</figcaption></figure><ul><li><strong>Frontend</strong>: a static site on Nginx, which also proxies /api/* so the browser only talks to one origin.</li><li><strong>Event, Program and Registration services</strong>: <a href="https://ballerina.io/">Ballerina</a> microservices on a shared, private RDS PostgreSQL instance.</li><li><strong>Analytics service</strong>: writes browser events into a self-hosted <a href="https://clickhouse.com/"><strong>ClickHouse</strong></a>.</li><li><strong>Observability</strong>: Prometheus + Grafana for metrics, and the <strong>OpenTelemetry Collector</strong> + <strong>Fluent Bit</strong> for traces and logs, stored in ClickHouse.</li><li><strong>Serverless</strong>: a Lambda that sends an SES email when seats run low, and a scheduled Lambda that exports analytics to S3 → Athena → QuickSight.</li><li><strong>Delivery</strong>: GitHub Actions with OIDC, and blue-green deploys with Helm.</li></ul><h4>Four separate flows run through the system:</h4><ol><li><strong>Request flow</strong>: Browser → Ingress → Nginx → service → RDS.</li><li><strong>Notification flow</strong>: Registration service → API Gateway → Lambda → SES.</li><li><strong>Analytics flow</strong>: browser → Analytics service → ClickHouse → Lambda → S3 → Athena → QuickSight.</li><li><strong>Telemetry flow</strong>: services and pods → OTel Collector / Prometheus → Grafana.</li></ol><p>Keeping these flows separate is itself a best practice. An analytics or telemetry outage should never break a registration.</p><h4>Key design decisions</h4><p>Every architecture is a set of trade-offs. These are the ones that shaped this platform:</p><ul><li><strong>Blue-green instead of rolling updates.</strong> The brief required 100% uptime. A rolling update mixes old and new versions during a deploy and has no explicit “go/no-go” point. Blue-green gives a smoke-tested cutover and a one-step rollback, at the cost of running two copies of every service.</li><li><strong>One RDS instance with per-service tables</strong>, not one database per service. Each service owns its own tables, and no service reads another’s tables. This keeps the logical separation of microservices without paying for and operating three RDS instances. The trade-off is a shared connection budget (see Section 4).</li><li><strong>Self-hosted ClickHouse.</strong> AWS has no managed ClickHouse, and a managed warehouse was too expensive for this budget. One ClickHouse instance serves both web analytics and telemetry storage, in separate databases.</li><li><strong>Metrics on Prometheus, logs and traces through OpenTelemetry.</strong> Prometheus’s pull model, PromQL and the kube-prometheus-stack dashboards are the de facto standard for Kubernetes metrics. Logs and traces benefit most from a push pipeline with batching and a pluggable backend.</li><li><strong>EC2 managed node groups, not Fargate.</strong> The observability stack needs DaemonSets (Fluent Bit on every node) and EBS-backed persistent volumes, which Fargate doesn’t support well.</li><li><strong>No NAT Gateway.</strong> Nodes run in public subnets with SSH disabled, and the export Lambda reaches S3 through a free Gateway VPC endpoint. This saves a fixed hourly cost, at the price of a larger network attack surface. It’s acceptable for coursework; in production I’d use private subnets.</li><li><strong>Ballerina for the services.</strong> HTTP services, clients and SQL are built into the language, and metrics and tracing are built into the runtime, so observability comes from configuration instead of instrumentation code.</li></ul><h3>1. AWS Foundations</h3><p>The essentials, done before creating any resources:</p><ul><li><strong>Secure the root account</strong>: enable MFA, set a <strong>budget alert</strong> (the EKS control plane bills about $0.10/hour even when idle), then stop using root.</li><li><strong>Use a scoped IAM user, not </strong><strong>AdministratorAccess.</strong> I split its permissions into small single-purpose policies, and scoped them with a <strong>naming convention</strong>: every resource I create by hand starts with new-event-*, and the policies only allow that prefix. The policies are in <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/tree/main/iam-policies">iam-policies/</a>.</li><li><strong>Test that least privilege works</strong> by confirming that out-of-scope actions fail (aws iam create-user ... → AccessDenied).</li><li><strong>Never let a user change its own permissions.</strong> My IAM user can <em>read</em> its own policies but not attach new ones, so it can’t quietly grant itself AdministratorAccess.</li><li><strong>Be honest about limits.</strong> SES, API Gateway, Glue and Athena don’t scope cleanly to resource ARNs, so those statements use Resource: &quot;*&quot;. Document that rather than pretending the policy is tighter than it is.</li><li><strong>Keep human and CI credentials separate.</strong> My access keys stay on my machine, outside the repo. CI uses a separate, short-lived OIDC role (Section 8).</li><li><strong>Use one region</strong> for every service (I used us-east-1, which also has full QuickSight support). Cross-region calls add latency, cost and complexity.</li></ul><h3>2. The EKS Cluster</h3><blockquote><strong>Best practice: define infrastructure as code.</strong></blockquote><p>The whole cluster is in one file, <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/infra/eksctl-cluster.yaml">infra/eksctl-cluster.yaml</a>: a managed node group of t3.medium nodes across two AZs, with SSH disabled.</p><pre>eksctl create cluster -f infra/eksctl-cluster.yaml</pre><p>Three things to do immediately afterwards:</p><ol><li><strong>Fix storage.</strong> On Kubernetes 1.30 the default gp2 StorageClass uses a provisioner that has been removed, so PVCs stay Pending. Install the <strong>EBS CSI driver</strong> add-on (with an IRSA role) and make <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/infra/storageclass-gp3.yaml">gp3</a> the default with volumeBindingMode: WaitForFirstConsumer, so each volume is created in the same AZ as its pod.</li><li><strong>Create one entry point.</strong> Use a single ingress-nginx LoadBalancer for the whole platform, not one per service.</li><li><strong>Separate workloads by namespace</strong>: app, data and observability, each with its own RBAC scope, resource dashboards and blast radius. Be aware that Secrets are namespaced, so a credential used in two namespaces (such as the ClickHouse password) needs a copy in each one, and each copy needs updating when you rotate it.</li></ol><p>Other cluster decisions:</p><ul><li><strong>Keep the cluster file in sync with reality.</strong> When I scaled the node group (Section 7), I also updated desiredCapacity in the eksctl file, so rebuilding from scratch gives the same cluster.</li><li><strong>Use EKS Access Entries</strong> for in-cluster permissions rather than editing the legacy aws-auth ConfigMap. They&#39;re managed through the AWS API and can be scoped to a namespace.</li><li><strong>Use IRSA for cluster add-ons.</strong> The EBS CSI driver gets its AWS permissions through its own service account role, not through the node’s instance role, so no other pod on the node inherits them.</li></ul><h3>3. The Data Layer</h3><blockquote><strong>Best practice: keep databases private and secrets out of git.</strong></blockquote><ul><li>RDS is created with --no-publicly-accessible and --storage-encrypted, in the cluster&#39;s security group. The schema is applied from a <strong>short-lived </strong><strong>psql pod inside the cluster</strong> instead of exposing the database.</li><li>All credentials are <strong>Kubernetes Secrets</strong>, referenced through secretKeyRef or the chart&#39;s existingSecret, and never written into values files.</li><li>Each service owns its own tables (<a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/local/init.sql">schema</a>), and the schema uses database constraints (CHECK (seats_available &gt;= 0), foreign keys) as a final safety net behind the application logic.</li><li>ClickHouse runs as a single-node StatefulSet on EBS (<a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/clickhouse/values.yaml">values</a>). With one replica, ClickHouse Keeper (the coordination service) isn’t needed, which keeps it cheap. Two gotchas:</li><li>Bitnami’s free images moved to bitnamilegacy/*. These still work but are frozen with no updates, so plan a migration to the official image or an operator.</li><li>The chart only runs *.sh init scripts. A .sql file is <strong>silently skipped</strong>. Make schema bootstrap idempotent (CREATE TABLE IF NOT EXISTS) and check that it actually ran.</li></ul><h4><strong>Design analytical tables for their queries</strong></h4><p>The web_events table uses LowCardinality(String) for event_type and ORDER BY (event_type, event_timestamp), so the most common query (&quot;count clicks per day&quot;) reads very little data:</p><pre>CREATE TABLE web_events (<br>    session_id String,<br>    event_type LowCardinality(String),<br>    event_timestamp DateTime64(3),<br>    page String,<br>    payload String,<br>    ingested_at DateTime DEFAULT now()<br>) ENGINE = MergeTree<br>ORDER BY (event_type, event_timestamp);</pre><h3>4. Application Design</h3><h4>Make concurrent writes safe at the database</h4><p>Two users must never both get the last seat. Instead of read-then-write, use one atomic, conditional update (<a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/services/event-service/service.bal">event-service/service.bal</a>):</p><pre>UPDATE events<br>SET seats_available = seats_available - ${req.ticketCount}<br>WHERE event_id = ${eventId}::uuid AND seats_available &gt;= ${req.ticketCount}<br>RETURNING seats_available</pre><p>If no row comes back, there weren’t enough seats and nothing changed. No locks or transactions are needed.</p><h4>Keep side effects off the critical path</h4><p>The Registration service reserves seats, saves the registration, and <strong>only then</strong> fires a best-effort low-seat notification. If the notification fails, it’s logged, and the registration still succeeds.</p><p><strong>Be explicit about consistency gaps.</strong> Reserve-then-save spans two services with no distributed transaction. If the insert fails after a successful reservation, those seats stay decremented. I documented this in the code instead of hiding it. The production fix is a saga with a compensating “release seats” call, or a transactional outbox.</p><h4>Size connection pools for the number of pods</h4><p>Ballerina’s SQL client defaults to 15 connections <strong>per pod</strong>. With 3 services × 2 slots × HPA replicas, a db.t3.micro ran out of connection slots:</p><pre>FATAL: remaining connection slots are reserved for roles with privileges of the &quot;rds_reserved&quot; role</pre><p>CloudWatch showed a flat 72 connections regardless of traffic, which pointed to idle pools rather than real load. The fix was to cap the pool per pod (<a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/services/event-service/db.bal">db.bal</a>):</p><pre>connectionPool = { maxOpenConnections: 3, minIdleConnections: 1, maxConnectionLifeTime: 1800 }</pre><p><strong><em>Rule:</em></strong><em> </em><em>max pods × pool size must fit in the database&#39;s connection limit.</em></p><h4>Health checks that mean something</h4><p>Each /healthz endpoint runs SELECT 1 against its data store, and Kubernetes uses it for readiness and liveness probes. A pod that can&#39;t reach its database never receives traffic.</p><h4>First-party, privacy-conscious analytics</h4><p>Instead of a third-party SDK, the frontend loads a small <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/frontend/js/analytics.js">analytics.js</a> that captures three kinds of event, each chosen to answer one question about the landing page:</p><ul><li><strong>visit</strong>: how many people arrive, and from where (referrer, UTM parameters)?</li><li><strong>click</strong>: do they act on the registration buttons?</li><li><strong>scroll</strong>: which sections hold their attention (dwell time per section via IntersectionObserver)?</li></ul><p>Events are batched in the browser and flushed every 5 seconds. When the tab is hidden, the last batch goes out with navigator.sendBeacon so it isn&#39;t lost. Telemetry failures are ignored and never affect the page. Visitors are identified only by a random session ID, not personal data.</p><p>The Analytics service posts each batch to ClickHouse’s HTTP interface as JSONEachRow, so ClickHouse parses the JSON itself and no SQL is built by hand.</p><h4>One origin, one ingress rule</h4><p>The frontend’s <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/frontend/nginx.conf">nginx.conf</a> proxies /api/events, /api/registrations and the other API paths to Kubernetes Service names. The browser only ever talks to one origin, so there&#39;s no CORS setup, and the <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/ingress/ingress.yaml">Ingress</a> needs just one rule. The same config works unchanged in <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/local/docker-compose.yml">Docker Compose</a>, which runs the whole platform locally without an AWS account.</p><h4>Lean images, but test the base image</h4><p>Each <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/services/registration-service/Dockerfile">Dockerfile</a> is a <strong>multi-stage build</strong>: compile with the full Ballerina toolchain, then copy only the jar into a JRE image. The runtime image has no compiler or build tools.</p><p>But small isn’t always safe. Registration crashed <strong>only when seats fell below 10</strong>, with UnsatisfiedLinkError: netty_tcnative. Creating an HTTP client loads a native library built for glibc, and the Alpine (musl) image couldn&#39;t load it. Because it was a JVM error rather than an application error, it killed the whole pod. Switching to eclipse-temurin:21-jre-jammy fixed it. Small images can hide failures in code paths your tests don&#39;t reach.</p><h4>Configuration separate from code</h4><p>Secrets arrive as environment variables from Kubernetes Secrets. Non-secret runtime configuration lives in committed files baked into the image. Local defaults live in a gitignored Config.toml. Each kind of value has one clear home.</p><h3>5. Observability</h3><blockquote><strong>Best practice: collect all three signals over open standards, and query them from one place.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVaT4BoZ5u8VBDoRsYP2qQ.png" /><figcaption>Deployment Architecture</figcaption></figure><ul><li><strong>Traces</strong>: service → OTLP → OTel Collector → ClickHouse</li><li><strong>Logs</strong>: Fluent Bit DaemonSet → OTLP → OTel Collector → ClickHouse</li><li><strong>Metrics</strong>: Prometheus scrapes each service’s /metrics endpoint</li><li><strong>Grafana</strong> queries both Prometheus and ClickHouse</li></ul><p>The OpenTelemetry Collector is a <strong>vendor-neutral layer</strong>: to change backends, you change one exporter, not every service. ClickHouse was already running for analytics, so reusing it for logs and traces avoided adding two more stateful systems (Loki and Tempo).</p><h4>Instrument through configuration, not code</h4><p>Ballerina has telemetry built in. You enable it with observabilityIncluded = true at build time, then configure it at runtime:</p><pre># services/*/observability.toml, loaded via ENV BAL_CONFIG_FILES<br>[ballerina.observe]<br>metricsEnabled = true<br>metricsReporter = &quot;prometheus&quot;<br>tracingEnabled = true<br>tracingProvider = &quot;otel&quot;   # exports over OTLP gRPC</pre><pre>[ballerina.otel]<br>tracesEndpoint = &quot;http://otel-collector.observability.svc.cluster.local:4317&quot;</pre><p><strong>Why a file?</strong> I first passed these settings as -C CLI flags in the Helm args. Production pods crash-looped twice with unused command line argument, which never happened locally. Two details made it worse:</p><ul><li><strong>It hit the slot CI didn’t deploy.</strong> The smoke-tested pod was healthy, while the “safe rollback” slot crashed on its next restart. CI showed green.</li><li><strong>The chart’s </strong><strong>args were shared by blue and green</strong>, so a deploy meant for one slot changed both.</li></ul><p>Moving the config into a committed, secret-free TOML file removed that code path completely. Recovery each time was git revert plus an immediate helm upgrade --reuse-values, with no user impact.</p><h4>Protect and bound the Collector</h4><p>The important parts of <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/observability/otel-collector-values.yaml">otel-collector-values.yaml</a>:</p><pre>image:<br>  repository: otel/opentelemetry-collector-contrib   # the k8s distro has no ClickHouse exporter<br>processors:<br>  memory_limiter: { check_interval: 5s, limit_percentage: 80, spike_limit_percentage: 25 }<br>  batch: {}<br>exporters:<br>  clickhouse:<br>    database: otel<br>    ttl: 72h            # bounded retention<br>    create_schema: true<br>service:<br>  pipelines:<br>    traces: { receivers: [otlp], processors: [memory_limiter, batch], exporters: [clickhouse] }<br>    logs:   { receivers: [otlp], processors: [memory_limiter, batch], exporters: [clickhouse] }</pre><ul><li>Put memory_limiter <strong>before</strong> batch so a traffic spike doesn&#39;t OOM-kill the Collector.</li><li><strong>Bound retention everywhere.</strong> Telemetry has a shelf life: 72 hours for logs and traces, 2 days for Prometheus. Unbounded telemetry fills disks and costs money.</li><li><strong>Pick the right distribution.</strong> The default k8s Collector distribution doesn&#39;t include the ClickHouse exporter. Only contrib does.</li><li><strong>Validate before rollout.</strong> Helm chart merges can produce configs that look fine in the values file but fail at runtime. I hit this when trying to disable the chart’s default metrics pipeline: null crashed helm upgrade, and {} made the Collector refuse to start. The answer was a valid pipeline that never receives data. Run otelcol-contrib validate on the rendered config before deploying it.</li></ul><h4>Standardise on OTLP end to end</h4><p>Fluent Bit’s forward output into the Collector&#39;s fluentforward receiver connected fine and reported <strong>zero errors, and no logs ever arrived</strong>. Switching Fluent Bit to its native opentelemetry output (<a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/observability/fluent-bit-values.yaml">values</a>) fixed it within seconds. One protocol for both signals is simpler, and an agent reporting no errors doesn&#39;t prove data arrived. Check the destination.</p><h4>kube-prometheus-stack on a managed control plane</h4><p>Key settings in <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/observability/prometheus-values.yaml">prometheus-values.yaml</a>:</p><ul><li><strong>Disable the control-plane scrape targets</strong> (coreDns, kubeControllerManager, kubeEtcd, kubeScheduler, kubeProxy). On EKS these components are AWS-managed and not visible as pods.</li><li><strong>Persist Grafana and use </strong><strong>deploymentStrategy: Recreate.</strong> With a ReadWriteOnce volume, the default rolling update can deadlock with a Multi-Attach error when the new pod lands on a different node.</li><li><strong>Pass the ClickHouse datasource password with </strong><strong>--set-string</strong> from the live Secret at install time, never in the values file. I learned this after an automated helm upgrade --reuse-values kept carrying a placeholder password forward and quietly broke the ClickHouse datasource. The CI workflow now reads the password from the Secret on every run.</li><li><strong>Keep the Grafana admin credentials in an </strong><strong>existingSecret</strong>, not in chart values.</li></ul><h4>Ship monitoring with each service</h4><p>Each service’s Helm chart includes a <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/event-service/templates/podmonitor.yaml">PodMonitor</a>, so a new service is scraped as soon as it&#39;s deployed:</p><pre>kind: PodMonitor<br>metadata:<br>  labels:<br>    release: kube-prometheus-stack   # without this label, Prometheus ignores the monitor<br>spec:<br>  selector: { matchLabels: { app: {{ .Chart.Name }} } }<br>  podMetricsEndpoints: [{ port: metrics, path: /metrics, interval: 30s }]</pre><p>I used a PodMonitor rather than a ServiceMonitor because the Service only points at the live slot. Scraping pods directly gives metrics from <strong>both</strong> blue and green, so you can compare versions before cutting over.</p><h4>Grafana dashboard view</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bYNatSX2V0e1e_dNpBQTXA.png" /><figcaption>Distributed traces (<em>A </em><em>POST /registrations traced end to end: Registration → Event </em><em>/reserve → PostgreSQL</em>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7305j_Im6XO5K6PpOvW8GA.png" /><figcaption>Service API metrics (<em>Request rate, errors and latency percentiles for both slots</em>)</figcaption></figure><p>I built four dashboards, each for a different question:</p><ul><li><strong>Service API metrics</strong>: is a service healthy right now? (request rate, error rate, latency percentiles)</li><li><strong>Traces</strong>: where did a slow or failed request spend its time?</li><li><strong>Cluster logs</strong>: what did the pods say?</li><li><strong>Web analytics</strong>: what are visitors doing, in real time?</li></ul><p>The trace view is what made the architecture visible. It shows the synchronous Registration → Event call directly, and it’s the first place to look when registrations get slow.</p><p>Dashboards are exported to <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/tree/main/grafana-dashboards">grafana-dashboards/</a>, so they can be restored if the Grafana volume is lost. An even better approach is to commit them as ConfigMaps labelled grafana_dashboard: &quot;1&quot;, so Grafana&#39;s sidecar provisions them automatically on every install.</p><h3>6. Blue-Green Deployments with Helm</h3><blockquote><strong>Best practice: keep the previous version running so rollback is instant.</strong></blockquote><p>One chart renders <strong>both</strong> Deployments (&lt;service&gt;-blue and &lt;service&gt;-green), and the stable Service selects the live one (<a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/event-service/values.yaml">values.yaml</a>, <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/event-service/templates/service.yaml">service.yaml</a>):</p><pre>spec:<br>  selector:<br>    app: {{ .Chart.Name }}<br>    slot: {{ .Values.activeSlot }}   # blue | green</pre><p>Cutting over, or rolling back, is just a selector change. Both slots stay running, so the old version is always available as an instant rollback without a redeploy.</p><p>Each slot runs <strong>one replica by default</strong>, and the HPA adds more under load. Blue + green already gives two running instances per service, and on a small cluster every extra replica uses up the node pod limit (Section 7).</p><p>Lessons from running it:</p><ul><li><strong>Scope everything per slot</strong>: image, args, env and config. Anything shared can break both slots (see Section 5).</li><li><strong>Deploy immutable image tags</strong> (commit SHAs), not latest.</li><li>Set requests, limits, readiness and liveness probes on every container.</li></ul><h3>7. Scaling</h3><h4>Pods: HPA, PDB and anti-affinity</h4><p>Each slot has its own <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/event-service/templates/hpa.yaml">HPA</a> (CPU target 70%, 1–4 replicas), a <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/helm/event-service/templates/pdb.yaml">PDB</a> with minAvailable: 1, and preferred pod anti-affinity to spread replicas across nodes.</p><ul><li>HPA utilisation is measured <strong>against the CPU request</strong>. With 100m requested, it scales out at about 70m per pod, so set requests from kubectl top, not guesses.</li><li><strong>One HPA per slot</strong>, because each slot is its own Deployment. The live slot scales with real traffic while the idle slot stays at its minimum.</li><li>Right after a deploy, one service scaled from 1 to 4 replicas because of JVM startup CPU. That’s expected behaviour, not a bug. Tune HPA behavior or startup probes for JVM services.</li><li><strong>PDBs protect you during maintenance.</strong> Node upgrades and drains respect minAvailable, so a slot never loses its last pod to a voluntary disruption.</li><li><strong>Anti-affinity is <em>preferred</em>, not <em>required</em>.</strong> Replicas spread across nodes when possible, but can still be scheduled on a small cluster.</li></ul><h4>Nodes: pod count is a resource too</h4><p>With the AWS VPC CNI, every pod gets a VPC IP from the node’s ENIs, which caps the number of pods per node:</p><blockquote><em>max pods = ENIs × (IPs per ENI − 1) + 2 → </em><strong><em>t3.medium = 17</em></strong></blockquote><p>DaemonSets count towards that limit. At 2 nodes the cluster reached exactly 34 pods, and the next routine deploy got stuck:</p><pre>0/2 nodes are available: 2 Too many pods.</pre><p>CPU and memory looked fine, but the pod limit had been reached. I scaled to 3 nodes and updated the eksctl config to match. The same limit applies in reverse: scaling down from 3 nodes to 2, or pausing only some nodes, can leave pods stuck in Pending. For production, add <strong>Karpenter or Cluster Autoscaler</strong>, and consider <strong>VPC CNI prefix delegation</strong> early, because enabling it later means replacing the node group.</p><blockquote><strong>Before raising </strong><strong>maxReplicas, check:</strong> pods per node, database connections (pods × pool), realistic CPU requests, and that PDBs still allow node drains.</blockquote><h3>8. CI/CD: Keyless, Gated and Verified</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6oLerfYW_eDetxAO8kcaw.png" /><figcaption>CI/CD flow diagram</figcaption></figure><h4>OIDC instead of stored AWS keys</h4><p>GitHub Actions exchanges its OIDC token for a short-lived IAM role, so no AWS key is stored in GitHub. Scope the trust policy to one repository and branch:</p><pre>&quot;StringLike&quot;: {<br>  &quot;token.actions.githubusercontent.com:sub&quot;:<br>    &quot;repo:&lt;OWNER&gt;@*/new-event-cloud-service@*:ref:refs/heads/main&quot;<br>}</pre><blockquote><strong><em>Watch the </em></strong><strong><em>@*.</em></strong><em> GitHub&#39;s </em><em>sub claim can include immutable numeric IDs (</em><em>repo:OWNER@123/REPO@456:...). A policy written in the usual </em><em>repo:OWNER/REPO format looks correct and fails with a generic </em><em>Not authorized to perform sts:AssumeRoleWithWebIdentity. Decode your real token to check which format you get.</em></blockquote><p>The IAM role only needs eks:DescribeCluster. Permissions inside the cluster come from an <strong>EKS Access Entry</strong>.</p><h4>The pipeline</h4><ul><li><a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/.github/workflows/pr-checks.yml"><strong>PR checks</strong></a>: build every image and render every chart. This is a required check before merging, and it needs no cloud credentials.</li><li><strong>Per-service workflows</strong>: path-filtered, so only changed services are built. Images are pushed to GHCR tagged with the commit SHA (what gets deployed), the release version and latest. Buildx layer caching keeps builds fast. After a successful build, the workflow opens a PR that bumps the service&#39;s patch version. Ballerina.toml is excluded from the path filter, so merging that PR doesn&#39;t trigger another build.</li><li><a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/.github/workflows/deploy-service.yml"><strong>Reusable blue-green deploy</strong></a>:</li></ul><ol><li>Find the inactive slot.</li><li>Deploy the new SHA to it.</li><li><strong>Smoke-test that pod directly</strong> with port-forward, bypassing the live Service.</li><li>Only then flip activeSlot.</li></ol><p>All five services use this one workflow, so they’re all released the same way. A fix to the release process is made once.</p><ul><li><a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/.github/workflows/observability.yml"><strong>Observability workflow</strong></a>: runs helm template on all three observability charts <strong>before touching the cluster</strong>, then upgrades them one at a time with --wait. These are single-instance releases with no blue-green slot, so validating before deploying is the main safeguard.</li></ul><p>Measure zero downtime rather than assuming it: run a curl loop against the ingress during a deploy and confirm every response is a 200. During the deploy, only the inactive slot&#39;s pods should change. The live slot&#39;s pod names and ages should stay the same until the cutover.</p><h4>Least privilege for CI, and knowing when you’ve departed from it</h4><p>App deploys worked with AmazonEKSEditPolicy scoped to the app namespace. <strong>kube-prometheus-stack</strong> did not: it manages ClusterRoles, webhooks and CRDs, and Kubernetes&#39; privilege-escalation checks rejected one permission after another. For a single-developer project, I deliberately moved the CI role to cluster-admin and <strong>documented the trade-off</strong>: a larger blast radius, limited by an OIDC trust scoped to main of one repository with branch protection. A team project should use scoped bind/escalate grants instead.</p><h3>9. Serverless Integrations</h3><p>Not everything belongs in the cluster. An occasional email or a scheduled export is cheaper and simpler as a Lambda: there’s no always-on pod, and it scales to zero between runs.</p><ul><li><strong>Low-seat alerts</strong>: API Gateway → Lambda → SES (<a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/lambda/seat-threshold-notifier/index.js">code</a>), called asynchronously so it can’t fail a registration.</li><li><strong>Analytics export</strong>: a Lambda runs every 15 minutes, writes a daily rollup to a <strong>fixed S3 key per day</strong>, and Glue → Athena → QuickSight read it (<a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/lambda/clickhouse-quicksight-export/index.js">code</a>).</li></ul><h4>Lessons</h4><ul><li><strong>Make jobs idempotent.</strong> Because each day’s output goes to the same key, re-runs overwrite instead of duplicating.</li><li><strong>Check data types end to end.</strong> ClickHouse returns UInt64 counts as JSON <strong>strings</strong>, so QuickSight counted rows instead of summing values and produced plausible but wrong charts. toInt32(count()) fixed it.</li><li><strong>Export aggregates, not raw events.</strong> BI tools need daily counts per event type and page, not every click. Rolling data up before export keeps S3, Athena scans and QuickSight SPICE small and cheap.</li><li><strong>A Lambda in a VPC isn’t a pod.</strong> It can’t resolve cluster DNS or reach ClusterIPs, so ClickHouse needed a NodePort. Without a NAT Gateway, it also needed a free <strong>S3 Gateway VPC Endpoint</strong> to reach S3.</li><li><strong>Give each function its own role</strong> with only what it needs. The export Lambda can only PutObject into its one bucket.</li><li><strong>Test-invoke before scheduling.</strong> Networking and permission errors show up immediately instead of 15 minutes later. VPC-attached functions also need more than the default 3-second timeout.</li><li><strong>SES starts in sandbox mode</strong>, where both sender and recipient must be verified before any email is delivered.</li><li><strong>Real-time and batch paths serve different readers.</strong> Grafana queries ClickHouse live for engineers, and QuickSight refreshes hourly for business reporting.</li><li><strong>Known limitation:</strong> the export Lambda targets one node’s IP. If that node is replaced, the export stops until the setting is updated. An internal load balancer in front of the NodePort would remove this single point of failure.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P_CtC3oo7dACipuAlaJmYg.png" /><figcaption>QuickSight dashboard</figcaption></figure><h3>10. Day-2 Operations</h3><ul><li><strong>Quick health check</strong>: kubectl get pods -n app | grep -v &quot;1/1.*Running&quot; should return nothing. Also check which slot is live and which <strong>image SHA</strong> it runs, because a green CI run doesn&#39;t prove either.</li><li><strong>Secret rotation</strong>: Kubernetes doesn’t hot-reload Secrets injected as environment variables. Update the Secret, then kubectl rollout restart every Deployment that uses it, in every namespace that has a copy.</li><li><strong>Rotation order matters.</strong> For the RDS password: change it in RDS first, then update the Secret, then restart <strong>both</strong> slots of every service that uses it. For ClickHouse: update the copy in every namespace, then restart ClickHouse and everything that connects to it.</li><li><strong>Cost control</strong>: scale the node group to 0 when the cluster is idle. Workload specs stay in etcd and EBS volumes reattach on resume. The control plane, RDS and the load balancer keep billing, so budget for them. Use lifecycle rules on S3 (exports expire after 30 days) and TTLs on telemetry.</li><li><strong>Test API behaviour after every deploy.</strong> A <a href="https://github.com/NipunaMadhushan/new-event-cloud-service/blob/main/postman/new-event-api.postman_collection.json">Postman collection</a> runs against the live ingress with Newman.</li><li><strong>Incident playbook</strong>: write each incident down as symptom → cause → fix. Two examples from this project:</li></ul><ol><li><em>Rollout stuck on “old replicas pending termination”</em> after shrinking DB pools: the old pods were holding every connection, so new pods couldn’t become Ready. Delete the stale pods manually.</li></ol><p><em>2. Grafana stuck in </em><em>Init:0/1</em>: an RWO volume with a rolling update. Switch to Recreate.</p><p><em>3. A service crash-looping after a config change</em>: git revert, then run helm upgrade --reuse-values directly instead of waiting for CI. Check <strong>both</strong> slots.</p><ul><li><strong>Roll back first, investigate later.</strong></li><li><strong>Tear down completely.</strong> eksctl delete cluster removes only what eksctl created. Lambdas, API Gateway, EventBridge rules, S3 buckets, VPC endpoints, Glue crawlers and QuickSight need removing separately, and a consistent new-event-* prefix makes them easy to find.</li></ul><p>The repository <a href="https://github.com/NipunaMadhushan/new-event-cloud-service#readme">README</a> covers local development, the CI/CD workflows and API testing with Newman.</p><h3>What can do better for Production</h3><p>This article should also be clear about where the build falls short:</p><ul><li><strong>Networking</strong>: move nodes to private subnets, with NAT or VPC endpoints for all AWS services.</li><li><strong>CI permissions</strong>: replace cluster-admin with scoped bind/escalate grants, and use a separate role for the observability pipeline.</li><li><strong>Node scaling</strong>: add Karpenter or Cluster Autoscaler, and enable VPC CNI prefix delegation from the start.</li><li><strong>Secrets</strong>: use AWS Secrets Manager with the External Secrets Operator and automatic rotation, instead of copying Kubernetes Secrets between namespaces.</li><li><strong>Consistency</strong>: add a saga or outbox for the reserve-then-register flow.</li><li><strong>Alerting</strong>: add SLO-based Alertmanager rules (error rate, p95 latency) on top of the dashboards.</li><li><strong>Privacy</strong>: add a consent banner for analytics, and a retention and deletion policy for registration data.</li></ul><p><strong>Observability is an architectural decision, not an add-on</strong>, and it’s what makes every other practice verifiable. Each incident here was diagnosed from data: a trace waterfall, a flat connection graph, a Too many pods event.</p><p>Best practices are also easier to follow once you’ve seen why they exist. Every item in the checklist above is there because leaving it out caused a real problem.</p><p><strong>👉 </strong><a href="https://github.com/NipunaMadhushan/new-event-cloud-service"><strong>github.com/NipunaMadhushan/new-event-cloud-service</strong></a></p><p>What would you add to this list? Let me know in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a91eea81e998" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observe Ballerina Application Traces with DataDog]]></title>
            <link>https://nipunamadhushan96.medium.com/observe-ballerina-application-traces-with-datadog-16f25b77706a?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/16f25b77706a</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[ballerina]]></category>
            <category><![CDATA[datadog]]></category>
            <category><![CDATA[tracing]]></category>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 18:41:40 GMT</pubDate>
            <atom:updated>2024-09-13T09:20:04.065Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was written using Ballerina Swan Lake Update 10 (2201.10.0)</em></p><p><a href="https://ballerina.io/?utm_source=medium&amp;utm_medium=article&amp;utm_campaign=devrel&amp;utm_term=newrelicextension"><strong>Ballerina</strong></a> is an open-source, cloud-native programming language optimized for integration. It has the capability to let users observe application servers running in Ballerina. “<a href="https://ballerina.io/learn/observe-ballerina-programs/">Observe Ballerina Programs</a>” includes a complete guide on using observability in Ballerina.</p><p>In a previous <a href="https://medium.com/@nipunamadhushan96/observe-ballerina-metrics-with-datadog-7f08b8b9d7ee">article</a>, I focused on how to observe Ballerina metrics with DataDog. This article will help you observe traces of Ballerina applications with DataDog. Please follow the steps below to observe Ballerina Tracing in DataDog.</p><h3>1. Setup DataDog</h3><p>As the initial step, we need to set up the DataDog with an account. Please follow the steps given below.</p><h4>Create an account in DataDog</h4><p>You can create a new account <a href="https://learn.datadoghq.com/users/sign_up">here</a>. Select a billing plan according to your needs (A free plan is also included).</p><h4>Create an API key</h4><p>You need to create an API key for the DataDog agent. To create an API key,</p><ul><li><strong>Click Profile → Organization Settings → API keys</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MDwyZPIfZYwYJHtm" /><figcaption>Creating an API key in DataDog</figcaption></figure><p>Creating an API key in DataDog</p><p>Click <a href="https://docs.datadoghq.com/account_management/api-app-keys/">here</a> to read more about the API keys in DataDog.</p><h4>Setup DataDog Agent</h4><p>After setting up your DataDog account, you need to set up a DataDog Agent in your instance.</p><p>You can follow this <a href="https://docs.datadoghq.com/agent/?tab=Linux">documentation</a> to get started with the DataDog agent on your local machine.</p><p>You need to include the API key you generated in your DataDog account to <strong>datadog.yaml </strong>in the <strong>datadog-agent/etc </strong>folder.</p><p>Then you need to use the following configurations in the <strong>datadog.yaml.</strong></p><p>To view traces in DataDog, we need to enable the APM (Application Performance Monitoring) in your DataDog agent.</p><pre>apm_config:<br>  enabled: true</pre><p>Ballerina uses OpenTelemetry to provide traces. Therefore we need to setup OpenTelemetry configurations as follows.</p><pre>otlp_config:<br>  receiver:<br>    protocols:<br>        grpc:<br>          endpoint: 0.0.0.0:4317</pre><h3>2. Setup Ballerina Application</h3><p>For this article, I have used a sample Ballerina application for online shopping and it can be found <a href="https://github.com/NipunaMadhushan/ballerina-observability-samples/tree/main/online-shopping-service-example">here</a>.</p><p>To observe Ballerina applications, you need to follow the following steps.</p><h4>Include observability in the Ballerina project</h4><p>We need to add the following to the <strong>Ballerina.toml</strong> in your Ballerina project.</p><pre>[build-options]<br>observabilityIncluded=true</pre><p>By default, when you are creating a new Ballerina project, the above build-option will be included in the Ballerina.toml.</p><p>Then you need to import the Ballerina extension for Jaeger in your project.</p><pre>import ballerinax/jaeger as _;</pre><h4>Setup Runtime Configurations</h4><p>We need to set up runtime configurations in the Config.toml file where the user needs to specify the metrics provider.</p><pre>[ballerina.observe]<br>tracingEnabled=true<br>tracingProvider=&quot;jaeger&quot;<br><br>[ballerinax.jaeger]<br>agentHostname=&quot;localhost&quot;<br>agentPort=4317 </pre><p>Check out the complete guide on how to observe traces in Ballerina programs <a href="https://ballerina.io/learn/observe-tracing/">here</a>.</p><h3>3. Observe traces in DataDog</h3><p>After setting up the Ballerina Application and the DataDog agent, you can run the Ballerina application and send some requests to the Ballerina service.</p><p>Then go to <strong>APM → Traces </strong>in the DataDog to view traces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wa8hBsOhYbrShZwwqYO5Q.png" /><figcaption>Trace Explorer in DataDog</figcaption></figure><p>You can filter the traces with the service name, resource, operation name, span kind, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBSGXc-9hAPPYCyTrOsEWA.png" /><figcaption>Ballerina application traces in DataDog</figcaption></figure><p>Once you select a trace, you can get more information with the tags attached to the span.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mgb5qyZZ7KCm28tbQvDACQ.png" /><figcaption>Span tags for a given span</figcaption></figure><p>Please feel free to share your thoughts below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16f25b77706a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Do We Need Observability in Integrations? Insights from Ballerina]]></title>
            <link>https://nipunamadhushan96.medium.com/why-do-we-need-observability-in-integrations-insights-from-ballerina-a26d551e094f?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a26d551e094f</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[tracing]]></category>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Wed, 17 Jul 2024 04:38:36 GMT</pubDate>
            <atom:updated>2024-07-17T10:24:13.048Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6S4LDSg40EltPXbSFhGrYA.png" /><figcaption>Ballerina Integrations with Observability</figcaption></figure><p>In today’s complex, distributed software systems, integrations play a crucial role in connecting various components and services. As these integrations become more intricate, the need for observability becomes paramount. Let’s explore why observability is essential in integrations and how Ballerina, a modern programming language designed for cloud-native applications, supports this critical aspect.</p><h3>Understanding Observability</h3><p>Observability is the ability to measure the internal states of a system by examining its outputs. In the context of integrations, it allows developers and operations teams to gain insights into their interconnected systems’ behaviour, performance, and health.</p><h3>Why Observability Matters in Integrations</h3><p>In the context of integrations, where multiple systems and teams often intersect, observability becomes the glue that holds everything together in the context of integrations, where multiple systems and teams often intersect. It provides the visibility, insights, and data needed to effectively manage, optimize, secure, and evolve complex integrated systems. As integrations become more central to business operations, investing in robust observability becomes not just beneficial but essential for maintaining a competitive edge and operational excellence. The following are the key factors why observability matters the most in integrations.</p><h4>a) Complexity Management:</h4><p>Integrations often involve multiple services, APIs, databases, and external systems interacting in complex ways. Observability provides a clear view of these interactions, helping teams to: <em>map data flows across systems, understand dependencies between services, visualize the entire integration landscape, and identify potential single points of failure.</em></p><blockquote><em>Example: In a micro-services architecture, an order processing system might interact with inventory, payment, and shipping services. Observability tools can create a service map, showing how these components interact and depend on each other.</em></blockquote><h4>b) Performance Optimisation:</h4><p>Observability allows teams to monitor and optimize the performance of their integrations by: <em>identifying bottlenecks in data processing or transmission, measuring response times across different services, tracking resource utilization (CPU, memory, network), and analyzing patterns in usage and load.</em></p><blockquote><em>Example: Through observability, a team might discover that a particular API call is causing slowdowns during peak hours. This insight allows them to optimize that specific endpoint or implement caching strategies.</em></blockquote><h4>c) Troubleshooting:</h4><p>When issues arise in integrated systems, observability becomes crucial for: <em>quickly isolating the source of problems, tracing errors across multiple services, understanding the context and conditions leading to failures, and reproducing issues for faster resolution.</em></p><blockquote><em>Example: If a customer reports a failed transaction, observability tools can help trace the transaction across all involved services, pinpointing where the failure occurred and under what conditions.</em></blockquote><h4>d) Proactive Maintenance:</h4><p>With proper observability, teams can shift from reactive to proactive maintenance by: <em>setting up alerts for anomalies or threshold breaches, predicting potential issues based on trend analysis, conducting capacity planning based on observed usage patterns, and identifying areas for preventive maintenance.</em></p><blockquote><em>Example: Observing increasing latency in database queries over time might prompt a team to optimize indexes or scale their database before it impacts users.</em></blockquote><h4>e) Security and Compliance:</h4><p>Observability plays a crucial role in maintaining security and meeting compliance requirements by: <em>tracking and auditing data access and modifications, monitoring for unusual patterns that might indicate security breaches, ensuring data handling complies with regulations like GDPR or HIPAA, and providing evidence for compliance audits.</em></p><blockquote><em>Example: In a healthcare integration, observability tools can track who accessed patient data, when, and for what purpose, ensuring HIPAA compliance.</em></blockquote><h4>f) Business Insights:</h4><p>Beyond technical benefits, observability can provide valuable business insights: <em>understanding user behavior and preferences, tracking key performance indicators (KPIs) in real-time, identifying popular features or services, and informing data-driven business decisions.</em></p><blockquote><em>Example: Observing patterns in API usage might reveal that a particular feature is more popular than anticipated, informing product development priorities.</em></blockquote><h3>Ballerina’s Approach to Observability</h3><p>Ballerina, a language optimized for cloud-native applications and integrations, offers built-in support for observability. Let’s look at some examples of how Ballerina implements observability:</p><h4>a) Tracing:</h4><p>Ballerina provides distributed tracing capabilities out of the box. Here’s a simple example which demonstrates how to add tracing to a simple HTTP service in Ballerina:</p><pre>import ballerina/http;<br>import ballerina/observe;<br>import ballerinax/jaeger as _;<br><br>@http:ServiceConfig {<br>  basePath: &quot;/hello&quot;<br>}<br>service HelloService on new http:Listener(8080) {<br>  resource function sayHello(http:Caller caller, http:Request request, string name) {<br>    // Start a span<br>    int spanId = check observe:startSpan(&quot;Greeting&quot;);<br>    // Your business logic here<br>    string response = &quot;Hello, &quot; + name + &quot;!&quot;;<br>    // End the span<br>    check observe:finishSpan(spanId);<br>    // Send the response<br>    check caller-&gt;respond(response);<br>  }<br>}</pre><h4>b) Metrics:</h4><p>Ballerina also supports collecting and exposing metrics. Here’s an example which shows how to define and use a counter metric to track the total number of requests:</p><pre>import ballerina/http;<br>import ballerina/observe;<br>import ballerinax/prometheus as _;<br><br>// Define a counter metric<br>observe:Counter requestCounter = new(&quot;total_requests&quot;);<br>@http:ServiceConfig {<br>  basePath: &quot;/hello&quot;<br>}<br>service HelloService on new http:Listener(8080) {<br>  resource function sayHello(http:Caller caller, http:Request request, string name) {<br>    // Increment the counter<br>    requestCounter.increment(1);<br>    string response = &quot;Hello, &quot; + name + &quot;!&quot;;<br>    check caller-&gt;respond(response);<br>  }<br>}</pre><h4>c) Logs:</h4><p>Ballerina provides a built-in logging module for easy log management. The following example demonstrates how to add informational logs to track the flow of requests and responses.</p><pre>import ballerina/log;<br>import ballerina/http;<br><br>@http:ServiceConfig {<br>  basePath: &quot;/hello&quot;<br>}<br>service HelloService on new http:Listener(8080) {<br>  resource function sayHello(http:Caller caller, http:Request request, string name) {<br>    log:printInfo(&quot;Received request for name: &quot; + name);<br>    string response = &quot;Hello, &quot; + name + &quot;!&quot;;<br>    check caller-&gt;respond(response);<br>    log:printInfo(&quot;Sent response for name: &quot; + name);<br>  }<br>}</pre><p>You can find more information on how to observe Ballerina programs <a href="https://ballerina.io/learn/observe-ballerina-programs/">here</a>.</p><h3>Benefits of Ballerina’s Observability Features</h3><p>Ballerina provide developers with the tools needed to build observable systems from the ground up, reducing the complexity typically associated with adding comprehensive observability to integration projects. The following factors show how Ballerina’s observability features help the users to develop and maintain large-scale cloud-native applications and integrations.</p><h4>a) Easy Integration:</h4><ul><li><em>Built-in Support:</em> Observability features are native to Ballerina, requiring no external libraries or complex setups.</li><li><em>Low Code Overhead:</em> Minimal code changes are needed to enable observability, often just a few lines or annotations.</li><li><em>Automatic Instrumentation:</em> Many observability features are automatically applied, reducing developer effort.</li></ul><h4>b ) Comprehensive Coverage:</h4><ul><li><em>Unified Approach: </em>Ballerina provides a cohesive set of tools covering logs, metrics, and traces.</li><li><em>End-to-End Visibility:</em> Observability spans from client requests to backend services and database calls.</li><li><em>Custom Metrics and Spans:</em> Developers can easily define and track custom metrics and traces relevant to their specific use cases.</li></ul><h4>c) Cloud-Native Ready:</h4><ul><li><em>Kubernetes Integration:</em> Ballerina’s observability features work seamlessly in containerized and Kubernetes environments.</li><li><em>Prometheus Compatibility:</em> Metrics can be easily exposed in Prometheus format, a standard in cloud-native monitoring.</li><li><em>Distributed Tracing:</em> Support for distributed tracing aligns with micro-services and cloud architectures.</li></ul><h4>d) Performance Optimized:</h4><ul><li><em>Low Overhead:</em> Observability features are designed to have minimal impact on application performance.</li><li><em>Sampling:</em> Tracing can be configured with sampling to reduce overhead in high-traffic scenarios.</li><li><em>Async Processing:</em> Many observability operations are handled asynchronously to avoid blocking the main execution path.</li></ul><h4>e) Extensibility:</h4><ul><li><em>Pluggable Architecture:</em> Ballerina’s observability can be extended to support various backends (e.g., Jaeger and Zipkin for tracing, Prometheus for metrics, DataDog and NewRelic for both metrics and tracing).</li><li><em>Custom Observers:</em> Developers can create custom observers for specific needs.</li></ul><h3>Conclusion</h3><p>Observability is not just a nice-to-have feature in modern integrations; it’s a necessity. It provides the visibility needed to effectively manage, optimize, and troubleshoot complex integrated systems. Ballerina’s built-in observability features demonstrate how modern languages are evolving to meet this crucial need, making it easier for developers to create observable, maintainable, and robust integrations.</p><p>By leveraging these observability features, teams can ensure their integrations are functional, transparent, performant, and ready for the challenges of cloud-native environments.</p><p>Please feel free to share your thoughts below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a26d551e094f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observe Ballerina Metrics with DataDog]]></title>
            <link>https://nipunamadhushan96.medium.com/observe-ballerina-metrics-with-datadog-7f08b8b9d7ee?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f08b8b9d7ee</guid>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[datadog]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[metrics-dashboard]]></category>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Thu, 04 Jul 2024 05:47:00 GMT</pubDate>
            <atom:updated>2024-07-09T05:56:44.517Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was written using Ballerina Swan Lake Update 9 (2201.9.1)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T6iWD1kbynjQL6eaaw3_mw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Luke Chesser</a> on <a href="https://unsplash.com/photos/graphs-of-performance-analytics-on-a-laptop-screen-JKUTrJ4vK00?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><a href="https://ballerina.io/?utm_source=medium&amp;utm_medium=article&amp;utm_campaign=devrel&amp;utm_term=newrelicextension"><strong>Ballerina</strong></a> is an open source, cloud-native programming language optimized for integration. It has the capability to let users observe application servers running in Ballerina. “<a href="https://ballerina.io/learn/observe-ballerina-programs/">Observe Ballerina Programs</a>” includes a complete guide on using observability in Ballerina.</p><p>This article will help you observe Ballerina applications with DataDog. Please follow the steps below to observe Ballerina Metrics in DataDog.</p><h3><strong>1. Setup DataDog</strong></h3><p>As the initial step, we need to set up the DataDog with an account. Please follow the steps given below.</p><h4>Create an account in DataDog</h4><p>You can create a new account <a href="https://learn.datadoghq.com/users/sign_up">here</a>. Select a billing plan according to your needs (free plan is also included).</p><h4>Add Prometheus in the Integrations for your account</h4><p>You need to add Prometheus in the Integrations. Please go to <strong>“Integrations”</strong> tab and search for Prometheus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eF4sKJsaqqgUTeO9" /><figcaption>Adding Prometheus in DataDog Integrations</figcaption></figure><h4>Create an API key</h4><p>You need to create an API key for the DataDog agent. To create an API key,</p><ul><li><strong>Click Profile → Organization Settings → API keys</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0pW4DPQmBkzGhEnX" /><figcaption>Creating an API key in DataDog</figcaption></figure><p>Click <a href="https://docs.datadoghq.com/account_management/api-app-keys/">here</a> to read more about the API keys in DataDog.</p><h3><strong>Setup DataDog Agent</strong></h3><p>After setting up your DataDog account, you need to set up a DataDog Agent in your instance.</p><p>Once you add Prometheus by following the previous step, you will get a guide to configure a DataDog agent in your instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uN5uuoS9euuojuSo" /><figcaption>Prometheus configurations for DataDog agent</figcaption></figure><p>You can follow the instructions given in the above configuration to set up a DataDog agent.</p><p>You need to include the API key you generated in your DataDog account to <strong>datadog.yaml </strong>in the <strong>datadog-agent/etc </strong>folder.</p><p>A sample of the <strong>conf.yaml</strong> file which you should include in the <strong>prometheus.d</strong> folder can be found <a href="https://drive.google.com/file/d/1heH49rvkRkSJUamrCHyC7Y3tWmY339_x/view?usp=sharing">here</a>.</p><h3><strong>Setup Ballerina Application</strong></h3><p>To observe metrics in the Ballerina applications/programs, you need to follow the following steps.</p><h4>Include observability in the Ballerina project</h4><p>We need to add the following to the <strong>Ballerina.toml</strong> in your Ballerina project.</p><pre>[build-options]<br>observabilityIncluded=true</pre><p>By default, when you are creating a new Ballerina project, the above build-option will be included in the Ballerina.toml.</p><p>Then you need to import the Ballerina extension for Prometheus in your project.</p><pre>import ballerinax/prometheus as _;</pre><h4>Setup Runtime Configurations</h4><p>We need to set up runtime configurations in the Config.toml file where the user needs to specify the metrics provider.</p><pre>[ballerina.observe]<br>metricsEnabled=true<br>metricsReporter=&quot;prometheus&quot;</pre><p>Check out the complete guide on how to observe Ballerina programs <a href="https://ballerina.io/learn/observe-ballerina-programs/">here</a>.</p><h3><strong>Observe Metrics in DataDog</strong></h3><p>After setting up the Ballerina Application and the DataDog, you can run the Ballerina application. You can observe the metrics in the DataDog under the <strong>“Metrics”</strong> tab in the left navigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eMyKHh06aYM8f70K" /><figcaption>Metrics Explorer in DataDog</figcaption></figure><p>You can add filters and use functions in the DataDog to visualize what you want with the metrics provided by Ballerina.</p><p>The following metrics are already available in DataDog.</p><ul><li>response_time_seconds_value</li><li>response_time_seconds</li><li>response_time_nanoseconds_total_value</li><li>requests_total_value</li><li>response_errors_total_value</li><li>inprogress_requests_value</li><li>kafka_publishers_value</li><li>kafka_consumers_value</li><li>kafka_errors_value</li></ul><p>We have created a dashboard in the DataDog to observe metrics in Ballerina You can get the applications <a href="https://drive.google.com/file/d/1y9FUIvBhUjmFUYwEbKUENWtrwHxLZVuX/view?usp=sharing">here</a>.</p><p>You can create a new dashboard in DataDog under the <strong>“Dashboards”</strong> tab in the left navigation. After creating the new dashboard, go to the <strong>“Configure”</strong> tab in the dashboard. Import the dashboard.json file provided above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eIqY7algiH-nmmYz" /><figcaption>Importing a dashboard json</figcaption></figure><p>The Ballerina Dashboard in the DataDog will be displayed as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WC0hkyNvDhFP02kp" /><figcaption>Ballerina Dashboard in DataDog</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pZRtbZsMifVjxDBVzMExoA.png" /><figcaption>Ballerina SQL Metrics in DataDog</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f08b8b9d7ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ballerina Observability Manual Instrumentation]]></title>
            <link>https://nipunamadhushan96.medium.com/ballerina-observability-manual-instrumentation-8f1cc03e5cab?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f1cc03e5cab</guid>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Fri, 02 Feb 2024 11:46:43 GMT</pubDate>
            <atom:updated>2024-02-07T09:44:46.515Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was written using Ballerina Swan Lake Update 8 (2201.8.4)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhAi8DPJ8_GmBskHF_JNXQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@techdailyca?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Tech Daily</a> on <a href="https://unsplash.com/photos/black-and-silver-laptop-computer-ztYmIQecyH4?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><a href="https://ballerina.io/?utm_source=medium&amp;utm_medium=article&amp;utm_campaign=devrel&amp;utm_term=newrelicextension"><strong>Ballerina</strong></a> is an open source, cloud-native programming language optimized for integration. It has the capability to let users observe application servers running in Ballerina. “<a href="https://ballerina.io/learn/observe-ballerina-programs/">Observe Ballerina Programs</a>” includes a complete guide on using observability in Ballerina.</p><p>This article focuses on how to use Ballerina Observability Manual Instrumentation, where the user can use customized metrics and spans as well as access the metric and span data in a Ballerina application.</p><h3><strong>Customize Metrics</strong></h3><p>Users can create customized metrics using the ballerina/observe library in Ballerina.</p><p>There are two metric types in Ballerina.</p><ol><li><strong>Counter</strong> — Cumulative metric that represents a single <a href="https://en.wikipedia.org/wiki/Monotonic_function">monotonically increasing counter</a> whose value can only increase or be reset to zero on restart.</li><li><strong>Gauge</strong> — A metric that represents a single numerical value that can arbitrarily go up and down.</li></ol><h4><strong>Generate counter metrics</strong></h4><p>Counter metrics can be used to measure counts which will only be increased or be reseted to zero (e.g.; total number of orders, total number of requests, etc.).</p><blockquote>Create</blockquote><p>You can define a counter metric as follows.</p><pre>observe:Counter totalOrders = new (“total_orders”);</pre><p>A description can also be added when you are defining the metric.</p><pre>observe:Counter totalOrders = new (“total_orders”, desc = “Total quantity required”);</pre><p>Usually metrics have tags, which can be used to filter when we are observing the metric data. We can pass a set of tags when we are defining the metric.</p><pre>map&lt;string&gt; counterTags = { &quot;method&quot;: &quot;GET&quot;, &quot;order-type&quot;: &quot;takeaway&quot;};<br>observe:Counter totalTakeawayOrders = new (&quot;total_orders&quot;, desc = &quot;Total quantity required&quot;, tags = counterTags);</pre><blockquote>Register</blockquote><p>The counter can be registered with the global metrics registry. Therefore, it can be looked up later without having the reference of the counter that was created. Also, only the registered counters will be reported to the Metrics reporter such as <a href="https://prometheus.io/">Prometheus</a>. In case, if there is already another non counter metric registered with the same metric name, then there will be an error returned. But if it’s another counter instance, then the registered counter instance will be returned.</p><pre>observe:Counter totalOrders = new (&quot;total_orders&quot;, desc = &quot;Total quantity required&quot;);<br>error? result = totalOrders.register();<br>if (result is error) {<br>    log:printError(&quot;Error registering the counter metric &#39;total_orders&#39;: &quot;, result);<br>}</pre><blockquote>Unregister</blockquote><p>The counter can be unregistered with the global metrics registry if it is already registered. If a metrics is unregistered, then further it’ll not be included in metrics reporting.</p><pre>observe:Counter totalOrders = new (&quot;total_orders&quot;, desc = &quot;Total quantity required&quot;);<br>error? result = totalOrders.register();<br>if (result is error) {<br>    log:printError(&quot;Error registering the counter metric &#39;total_orders&#39;: &quot;, result);<br>}<br>totalOrders.unregister();</pre><blockquote>Increment</blockquote><p>The counter can be incremented without passing any params (defaulted to 1).</p><pre>observe:Counter totalOrders = new (&quot;total_orders&quot;, desc = &quot;Total quantity required&quot;);<br>totalOrders.increment();</pre><p>Counter can be incremented by a specific amount as well.</p><pre>observe:Counter totalOrders = new (&quot;total_orders&quot;, desc = &quot;Total quantity required&quot;);<br>totalOrders.increment(amount = 10);</pre><blockquote>Reset</blockquote><p>The counter can be resetted to default amount = 0.</p><pre>observe:Counter totalOrders = new (&quot;total_orders&quot;, desc = &quot;Total quantity required&quot;);<br>totalOrders.reset();</pre><blockquote>Get Value</blockquote><p>Counter metric value can be accessed as follows.</p><pre>observe:Counter totalOrders = new (&quot;total_orders&quot;, desc = &quot;Total quantity required&quot;);<br>int currentValue = totalOrders.getValue();</pre><p>A sample Ballerina application about how to use a customized counter metric with a REST service can be found in <a href="https://github.com/NipunaMadhushan/ballerina-observability-samples/tree/main/observability-manual-instrumentation/counter-metrics-sample">here</a>.</p><h4>Generate Gauge Metrics</h4><p>Gauge metrics can be used to measure values which will be increased or decreased (e.g.; number of ongoing orders, number of ongoing requests, response time, etc.).</p><blockquote>Create</blockquote><p>You can define a counter metric as follows.</p><pre>observe:Gauge ongoingOrders = new (&quot;total_ongoing_orders&quot;);</pre><p>A description can also be added when you are defining the metric.</p><pre>observe:Gauge ongoingOrders = new (&quot;total_ongoing_orders&quot;, desc = &quot;Total Ongoing Orders&quot;);</pre><p>We can add tags as well which is very similar to counter metrics.</p><pre>map&lt;string&gt; gaugeTags = {&quot;method&quot;: &quot;GET&quot;, &quot;order_type&quot; : &quot;takeaway&quot;};<br>observe:Gauge ongoingOrders = new (&quot;total_ongoing_orders&quot;,<br>                            desc = &quot;Total Ongoing Orders&quot;,<br>                            tags = gaugeTags);</pre><p>We can create gauge metrics with disable (empty) statistic configs as well.</p><pre>map&lt;string&gt; gaugeTags = {&quot;method&quot;: &quot;GET&quot;, &quot;order_type&quot; : &quot;takeaway&quot;};<br>observe:StatisticConfig[] statsConfigs = [];<br>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, <br>        desc = &quot;Total Ongoing Orders&quot;, tags = gaugeTags, statisticConfig = statsConfigs);</pre><p>When we need to config statistic configs, we need to do as follows.</p><pre>map&lt;string&gt; gaugeTags = {&quot;method&quot;: &quot;GET&quot;, &quot;order_type&quot; : &quot;takeaway&quot;};<br>observe:StatisticConfig[] statsConfigs = [];<br>observe:StatisticConfig config = { timeWindow: 30000, <br>        percentiles: [0.33, 0.5, 0.9, 0.99], buckets: 3 };<br>statsConfigs[0]=config; <br><br>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, <br>        desc = &quot;Total Ongoing Orders&quot;, tags = gaugeTags, statisticConfig = statsConfigs);</pre><blockquote>Register</blockquote><p>The gauge can be registered with the global metrics registry, therefore it can be looked up later without having the reference of the gauge that was created. Also, only the registered counters will be reported to the Metrics reporter such as Prometheus. In case, if there is already another non gauge metric registered, then there will be an error returned. But if it’s another gauge instance, then the registered gauge instance will be returned.</p><pre>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, desc = &quot;Total Ongoing Orders&quot;);<br>error? result = ongoingOrders.register();<br>if (result is error) {<br>    log:printError(&quot;Error registering the counter metric &#39;total_ongoing_orders&#39;: &quot;, result);<br>}</pre><blockquote>Unregister</blockquote><p>The gauge can be unregistered with the global metrics registry if it is already registered. If a metrics is unregistered, then further it’ll not be included in metrics reporting.</p><pre>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, desc = &quot;Total Ongoing Orders&quot;);<br>error? result = ongoingOrders.register();<br>if (result is error) {<br>    log:printError(&quot;Error registering the counter metric &#39;total_ongoing_orders&#39;: &quot;, result);<br>}<br>ongoingOrders.unregister();</pre><blockquote>Increment</blockquote><p>The gauge can be incremented without passing any params (defaulted to 1.0).</p><pre>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, desc = &quot;Total Ongoing Orders&quot;);<br>ongoingOrders.increment();</pre><p>Gauge can be incremented by a specific amount as well.</p><pre>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, desc = &quot;Total Ongoing Orders&quot;);<br>ongoingOrders.increment(amount = 10.0);</pre><blockquote>Decrement</blockquote><p>The gauge can be decremented without passing any params (defaulted to 1.0).</p><pre>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, desc = &quot;Total Ongoing Orders&quot;);<br>ongoingOrders.decrement();</pre><p>Similarly, gauge can be decremented by a specific amount as well.</p><pre>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, desc = &quot;Total Ongoing Orders&quot;);<br>ongoingOrders.decrement(amount = 10.0);</pre><blockquote>Set Value</blockquote><p>Gauge value can be set as follows.</p><pre>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, desc = &quot;Total Ongoing Orders&quot;);<br>ongoingOrders.setValue(100.0);</pre><blockquote>Get Value</blockquote><p>Gauge value can be accessed as well which is very similar to counter metric. But the value will be a float value instead of int.</p><pre>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, desc = &quot;Total Ongoing Orders&quot;);<br>float currentValue = ongoingOrders.getValue();</pre><blockquote>Get Snapshot</blockquote><p>Users can get the current snapshot of the statistics calculation based on the configurations passed to the gauge. If the statistics are disabled, then it’ll be returning nil ().</p><pre>map&lt;string&gt; gaugeTags = {&quot;method&quot;: &quot;GET&quot;, &quot;order_type&quot; : &quot;takeaway&quot;};<br>observe:StatisticConfig[] statsConfigs = [];<br>observe:StatisticConfig config = { timeWindow: 30000, <br>        percentiles: [0.33, 0.5, 0.9, 0.99], buckets: 3 };<br>statsConfigs[0]=config; <br><br>observe:Gauge ongoingOrders = new(&quot;total_ongoing_orders&quot;, <br>        desc = &quot;Total Ongoing Orders&quot;, tags = gaugeTags, statisticConfig = statsConfigs);<br><br>ongoingOrders.setValue(1.0);<br>ongoingOrders.setValue(2.0);<br>ongoingOrders.setValue(3.0);<br><br>observe:Snapshot[]? summarySnapshot = gaugeWithTags.getSnapshot();<br>if summarySnapshot is observe:Snapshot[] {<br>    io:println(summarySnapshot);<br>} else {<br>    io:println(&quot;No statistics available!&quot;);<br>}</pre><p>A sample Ballerina application about how to use a customized gauge metric with a REST service can be found in <a href="https://github.com/NipunaMadhushan/ballerina-observability-samples/tree/main/observability-manual-instrumentation/gauge-metric-sample">here</a>.</p><h4>Get Global Metrics</h4><p>While running Ballerina application, we can access the metrics that are registered in the global metrics registry.</p><p>We can get all the metrics as follows.</p><pre>observe:Metric[] metrics = observe:getAllMetrics();<br>foreach var metric in metrics {<br>    // Do something.<br>}</pre><p>We can also get a specific metric by using the metric name and the tags.</p><pre>map&lt;string&gt; tags = {&quot;method&quot;: &quot;GET&quot;, &quot;order_type&quot; : &quot;takeaway&quot;};<br>observe:Counter|observe:Gauge|() metric = observe:lookupMetric(&quot;total_ongoing_orders&quot;, <br>        tags = tags);<br>if metric is observe:Counter {<br>    // Do something<br>} else if metric is observe:Gauge {<br>    // Do something<br>} else {<br>    io:println(&quot;No Metric Found!&quot;);<br>}</pre><h4>Attach a Tag to Metrics</h4><p>A common tag (key &amp; value) can be attached to all the metrics registered in the global metric registry in Ballerina.</p><pre>error? result = check observe:addTagToMetrics(&quot;service_name&quot;, &quot;online-store-service&quot;);<br>if (result is error) {<br>    log:printError(&quot;Error adding tag to metrics: &quot;, result);<br>}</pre><h3>Customize Spans</h3><p>A single trace in distributed tracing consists of a series of tagged time intervals known as spans. Users can create customized spans by using the ballerina/observe library in Ballerina.</p><blockquote>Start a root span</blockquote><p>A customized root span can be started as follows.</p><pre>int spanId = observe:startRootSpan(&quot;Parent Span&quot;);</pre><blockquote>Start a child span</blockquote><p>We can start a child span and attach it to a parent span as follows.</p><pre>int spanId = observe:startRootSpan(&quot;Parent Span&quot;);<br>int spanId2 = checkpanic observe:startSpan(&quot;Child Span&quot;, parentSpanId = spanId);</pre><p>When no parentSpanId is given or a parentSpanId of -1 is given, a span is started as a child span to the current active span in the ootb system trace.</p><pre>int spanId = checkpanic observe:startSpan(&quot;Child Span&quot;);</pre><blockquote>Attach a tag to a span</blockquote><p>Usually spans have tags which are specific to the span. We can add tags to a span with a given spanId.</p><pre>_ = observe:addTagToSpan(spanId = spanId, “Tag Key”, “Tag Value”);</pre><p>When no spanId is provided or -1 is given, the defined tags are added to the current active span in the ootb system trace.</p><pre>var ret = observe:addTagToSpan(&quot;Tag Key&quot;, &quot;Tag Value&quot;);</pre><blockquote>Finish a span</blockquote><p>A span can be finished with a given spanId.</p><pre>var ret = observe:finishSpan(spanId);</pre><p>A sample Ballerina application about how to use customized spans with a REST service can be found in <a href="https://github.com/NipunaMadhushan/ballerina-observability-samples/tree/main/observability-manual-instrumentation/distributed-tracing-sample">here</a>.</p><h3>Make a Function Observable</h3><p>A function can be observable by using an annotation as follows.</p><pre>@observe:Observable<br>function processOrder(OrderType orderType) returns error? {<br>    // Do something<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f1cc03e5cab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observe Ballerina Integrations with New Relic Extension]]></title>
            <link>https://medium.com/ballerina-techblog/observe-ballerina-integrations-with-new-relic-extension-c6634097b061?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6634097b061</guid>
            <category><![CDATA[new-relic]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[ballerina]]></category>
            <category><![CDATA[metrics]]></category>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Fri, 15 Dec 2023 09:53:27 GMT</pubDate>
            <atom:updated>2025-08-28T05:07:24.546Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was written using Ballerina Swan Lake Update 8 (2201.8.4)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LnL_xO1vA9GYrPm-.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@adamaszczos?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Adam Nowakowski</a> on <a href="https://unsplash.com/photos/man-sitting-in-front-of-the-macbook-pro-D4LDw5eXhgg?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p><a href="https://ballerina.io/?utm_source=medium&amp;utm_medium=article&amp;utm_campaign=devrel&amp;utm_term=newrelicextension"><strong>Ballerina</strong></a> is an open source, cloud-native programming language optimized for integration. It has the capability to let users observe application servers running in Ballerina. A complete guide on how to use observability in Ballerina is included in<a href="https://ballerina.io/learn/observe-ballerina-programs/"> observe ballerina programs</a>.</p><p>In the previous<a href="https://medium.com/p/086948d045c7"> article</a>, I have explained how to observe Ballerina programs in New Relic with ballerinax/prometheus and ballerinax/zipkin extensions. This article focuses on how to observe Ballerina programs in<a href="https://newrelic.com/welcome-back"> <strong>New Relic</strong></a> with the ballerinax/newrelic<a href="https://github.com/ballerina-platform/module-ballerinax-newrelic"> observability extension</a>.</p><p>Users can observe metrics and traces in New Relic. Documentation is available on<a href="https://newrelic.com/blog/how-to-relic/a-quick-guide-to-getting-started-with-new-relic"> getting started with New Relic</a> about how to set up a new relic platform in your operating system.</p><p>I have used a <strong>social media application</strong> as a sample for this article and can be found in the<a href="https://github.com/NipunaMadhushan/ballerina-observability-samples/tree/main/social-media-demo-with-newrelic"> <strong>repository</strong></a>.</p><h3>Configure a Ballerina project to observe in New Relic</h3><p><em>Prerequisites</em></p><ol><li>Sign Up and Generate an API Key in <a href="https://newrelic.com/">New Relic</a>.</li></ol><ul><li>To configure the API key in Newrelic:</li><li>Go to <strong>Profile -&gt; API keys -&gt; Insights Insert key -&gt; Insert keys</strong> to create an account in New Relic.</li></ul><p>To enable observability in Ballerina program, include the following in Ballerina.toml.</p><pre>[build-options]<br>observabilityIncluded=true</pre><p>To observe Ballerina programs via New Relic, users need to configure publishing metrics and traces as well as the metrics reporter and the tracing provider in the Config.toml file, which should be created inside the project directory.</p><pre>[ballerina.observe]<br>metricsEnabled=true<br>metricsReporter=&quot;newrelic&quot;<br>tracingEnabled=true<br>tracingProvider=&quot;newrelic&quot;</pre><p>We can configure ballerinax/newrelic extension in the Config.toml as well.</p><pre>[ballerinax.newrelic]<br>apiKey=&quot;&lt;NEW_RELIC_LICENSE_KEY&gt;&quot;    # Mandatory Configuration.<br>tracingSamplerType=&quot;const&quot;          # Optional Configuration. Default value is &#39;const&#39;<br>tracingSamplerParam=1               # Optional Configuration. Default value is 1<br>tracingReporterFlushInterval=15000  # Optional Configuration. Default value is 15000 milliseconds<br>tracingReporterBufferSize=10000     # Optional Configuration. Default value is 10000<br>metricReporterFlushInterval=15000   # Optional Configuration. Default value is 15000 milliseconds<br>metricReporterClientTimeout=10000   # Optional Configuration. Default value is 10000 milliseconds</pre><p>Providing an apiKey in configurations is mandatory and other configurations are optional (use default configurations).</p><p>Users can configure the environment variable BALLERINA_NEWRELIC_API_KEY instead of apiKey in Config.toml. If both are configured, apiKey in Config.toml will be overwritten by the environment variable value. For the sample I am referring to in this article, I have used BALLERINA_NEW_RELIC_API_KEY environment variable.</p><p>Then include the following line into the bal file.</p><pre>import ballerinax/newrelic;</pre><h3>Observe Metrics</h3><p>Instead of using Prometheus as an intermediate metric reporter that remote writes the metrics to New Relic, Ballerina New Relic Observability Extension directly publishes metrics to New Relic on the following metric API <a href="https://metric-api.newrelic.com/metric/v1.">https://metric-api.newrelic.com/metric/v1.</a></p><p>Instrumentation of metrics is done using the <a href="https://github.com/newrelic/newrelic-telemetry-sdk-java">com.newrelic.telemetry</a>.</p><p>Available metrics in Ballerina applications can be found <a href="https://github.com/ballerina-platform/module-ballerinax-newrelic?tab=readme-ov-file#available-metrics">here</a>.</p><p>You can access the metrics that were published to the New Relic server in the New Relic query builder. You can view the metrics query data in graphical format, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*QsDFxLT5SglfLOsK.gif" /><figcaption>View metrics in New Relic</figcaption></figure><h3>Observe Traces</h3><p>Ballerina New Relic Observability Extension directly publishes traces to New Relic on the following trace API https://otlp.nr-data.net:4317. Traces are published to New Relic on OpenTelemetry format.</p><p>Instrumentation of traces is done using the <a href="https://github.com/open-telemetry/opentelemetry-java">io.opentelemetry</a> and GRPC protocol is used send traces.</p><p>You can access the traces that were published to the New Relic server in <a href="https://one.newrelic.com/distributed-tracing?account=4151712&amp;duration=1800000&amp;state=6933e0e8-390c-8b9d-8cc9-ef1786960010">New Relic traces</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*fJFEKmWBboIlY16Z.gif" /><figcaption>View traces in New Relic</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6634097b061" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ballerina-techblog/observe-ballerina-integrations-with-new-relic-extension-c6634097b061">Observe Ballerina Integrations with New Relic Extension</a> was originally published in <a href="https://medium.com/ballerina-techblog">Ballerina Swan Lake Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observe Ballerina Programs with New Relic]]></title>
            <link>https://medium.com/ballerina-techblog/observe-ballerina-programs-with-new-relic-086948d045c7?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/086948d045c7</guid>
            <category><![CDATA[metrics]]></category>
            <category><![CDATA[ballerinalang]]></category>
            <category><![CDATA[new-relic]]></category>
            <category><![CDATA[tracing]]></category>
            <category><![CDATA[observability]]></category>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Fri, 06 Oct 2023 20:23:17 GMT</pubDate>
            <atom:updated>2023-10-27T08:49:37.467Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was written using Ballerina Swan Lake Update 8 (2201.8.0)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_OcDyUZJ17B7enoL6EJjQ.jpeg" /><figcaption><a href="https://unsplash.com/photos/man-holding-black-smartphone-with-flat-screen-monitor-in-front-NDfqqq_7QWM">https://unsplash.com/photos/man-holding-black-smartphone-with-flat-screen-monitor-in-front-NDfqqq_7QWM</a></figcaption></figure><p><a href="https://ballerina.io/"><strong>Ballerina</strong></a> is an open source, cloud-native programming language optimized for integration. It has the capability to let users observe application servers running in Ballerina.</p><p>Observability in Ballerina consists of the three major pillars below.</p><ul><li><strong>Metrics</strong>: numeric values that are collected and aggregated over a period of time.</li><li><strong>Tracing</strong>: the activities that occur when a request/transaction occurs in the system from the point of entry to exit.</li><li><strong>Logging</strong>: text records of activities that occurred with relevant information along with the timestamp.</li></ul><p>A complete guide on how to use observability in Ballerina is included in <a href="https://ballerina.io/learn/observe-ballerina-programs/">Observe Ballerina Programs</a>.</p><p>This article focuses on how to observe Ballerina programs in <a href="https://newrelic.com/welcome-back"><strong>New Relic</strong></a>, which is a Software as a Service offering that focuses on performance and availability monitoring. Users can observe metrics and traces in New Relic. Documentation is available on <a href="https://newrelic.com/blog/how-to-relic/a-quick-guide-to-getting-started-with-new-relic">getting started with new relic</a> about how to set up a new relic platform in your operating system.</p><p>The following steps will guide you to set up a Ballerina project to be observed with New Relic. I have used the Ballerina Swan Lake Update 8 (2201.8.0) version and can be downloaded from <a href="https://ballerina.io/downloads/">here</a>.</p><p><strong>Setup ballerina project</strong></p><p>A new Ballerina project can be created by using the following command.</p><p><em>bal new &lt;PROJECT_NAME&gt;</em></p><p>Then a directory will be created which contains the Ballerina.toml file. By default, the following configuration will be added when you create a new project.</p><pre>[build-options]<br>observabilityIncluded=true</pre><p>In this post,, the following simple HTTP service will be used.</p><pre>import ballerina/http;<br><br>service /srvc on new http:Listener(8090) {<br>  resource function get success() returns string|error {<br>    return &quot;successful&quot;;<br>  }<br>}</pre><p><strong>Observe Metrics in New Relic</strong></p><p>To observe metrics in Ballerina programs, users need to configure publishing metrics and the metrics reporter in the Config.toml file, which should be created inside the project directory.</p><pre>[ballerina.observe]<br>metricsEnabled=true<br>metricsReporter=&quot;prometheus&quot;</pre><p>We use Prometheus as the metrics reporter since we cannot directly publish metrics into New Relic. Prometheus OpenMetrics integration can be done in two methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OFsDjZWrRH7xhVk8" /><figcaption>Prometheus OpenMetrics Integration for New Relic</figcaption></figure><p>Here, we focus on using the Prometheus server as an intermediate metrics reporter, which will push the data to the New Relic server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/0*-dPkJ1ylJkroyd_H" /><figcaption>Publishing Metrics from Ballerina Runtime to New Relic</figcaption></figure><p>First, we need to set up a Ballerina program to publish data into the Prometheus server. We need to create a Config.toml file in the Ballerina project directory, which includes the following.</p><pre>[ballerina.observe]<br>metricsEnabled=true<br>metricsReporter=&quot;prometheus&quot;<br><br>[ballerinax.prometheus]<br>port=9797<br>host=&quot;0.0.0.0&quot;</pre><p>Then include the following line into main bal file.</p><pre>import ballerinax/prometheus;</pre><p>Please follow the documentation in <a href="https://ballerina.io/learn/observe-metrics/">observe metrics</a> to find more details about how to observe Ballerina programs with Prometheus.</p><p>We need to push Prometheus data to the New Relic server via a remote write url. Remote write URL and the token can be generated from <a href="https://one.newrelic.com/marketplace/prometheus-remote-write-integration/home?account=4151712&amp;duration=1800000&amp;state=6933e0e8-390c-8b9d-8cc9-ef1786960010">integrate Prometheus data</a>. Documentation related to setting up Prometheus remote write integration can be found <a href="https://docs.newrelic.com/docs/infrastructure/prometheus-integrations/install-configure-remote-write/set-your-prometheus-remote-write-integration/">here</a>.</p><p>Then we need to add the remote write URL and token into the prometheus.yml file where you run the Prometheus server.</p><pre>remote_write:<br>  - url: https://metric-api.newrelic.com/prometheus/v1/write?prometheus_server=&lt;YOUR_DATA_SOURCE_NAME&gt;<br>    bearer_token: &lt;TOKEN&gt;</pre><p>When we run the sample Ballerina program given above, you can see the log given below.</p><pre>ballerina: started Prometheus HTTP listener 0.0.0.0:9797</pre><p>Then send HTTP requests to the Ballerina service as given below.</p><pre>curl http://localhost:8090/srvc/success</pre><p>You can access the metrics that were published to the New Relic server in the New Relic <a href="https://one.newrelic.com/data-exploration/query-builder?account=4151712&amp;duration=1800000&amp;state=30b4af86-f7fe-8994-cd61-e0a3477998a0">query builder</a>. You can view the metrics query data in graphical format, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u1HDg7bqzXN1xWoFF9TDmw.png" /><figcaption>Ballerina Metrics Representation in New Relic</figcaption></figure><p><strong>Observe Tracing in New Relic</strong></p><p>Tracing information in Ballerina projects can be published to New Relic by using ballerinax zipkin package. It initially publishes tracing data into Zipkin server via a Zipkin Exporter, but it can be used to publish tracing information into different trace APIs as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/0*ib0ZMlQSc7RWSXk0" /><figcaption>Publishing Tracing Data from Ballerina Runtime to New Relic</figcaption></figure><p>There are two different tracing data formats that the New Relic trace API accepts to be published into their servers.</p><ol><li>Zipkin format</li><li>New Relic format</li><li>Open Telemetry format</li></ol><p>We use Zipkin format for now since we are using the ballerinax/zipkin package in Ballerina. It has a Zipkin exporter, which uses HTTP protocol. The trace API used for the Zipkin data format is <a href="https://trace-api.newrelic.com/trace/v1">https://trace-api.newrelic.com/trace/v1</a>. A trace API key is required to publish into New Relic servers. Please follow the path below to generate a trace API key.</p><p><strong><em>Go to Profile -&gt; API keys -&gt; Insights Insert key -&gt; Insert keys to create an account in New Relic.</em></strong></p><p>For more information please refer to <a href="https://docs.newrelic.com/docs/distributed-tracing/trace-api/trace-api-general-requirements-limits/">Trace API requirements</a>.</p><p>We need to set up Ballerina program to publish tracing in Zipkin formatdata into the Zipkin server. We need to create a Config.toml file in the Ballerina project directory, which includes the following. Instead of host and port for Zipkin server, configure reporterEndpoint to pass trace API.</p><pre>[ballerina.observe]<br>tracingEnabled=true<br>tracingProvider=&quot;zipkin&quot;<br><br>[ballerinax.zipkin]<br>reporterEndpoint=&quot;https://trace-api.newrelic.com/trace/v1?Api-Key=&lt;NEW_RELIC_LICENSE_KEY&gt;&amp;Data-Format=zipkin&amp;Data-Format-Version=2&quot;</pre><p>Then include the following line into main bal file.</p><pre>import ballerinax/zipkin;</pre><p>When we run the sample Ballerina program given above, you can see the log given below.</p><pre>ballerina: started publishing traces to Zipkin on https://trace-api.newrelic.com/trace/v1</pre><p>Then send HTTP requests to the Ballerina service as given below.</p><pre>curl http://localhost:8090/srvc/success</pre><p>You can access the traces that were published to the New Relic server in <a href="https://one.newrelic.com/distributed-tracing?account=4151712&amp;duration=1800000&amp;state=6933e0e8-390c-8b9d-8cc9-ef1786960010">New Relic traces</a>. You can view the metrics query data in graphical format, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aPycCsoaDZu2UjSckLPMrA.png" /><figcaption>Ballerina Tracing Representation in New Relic</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=086948d045c7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ballerina-techblog/observe-ballerina-programs-with-new-relic-086948d045c7">Observe Ballerina Programs with New Relic</a> was originally published in <a href="https://medium.com/ballerina-techblog">Ballerina Swan Lake Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate Installers for Ballerina]]></title>
            <link>https://nipunamadhushan96.medium.com/installer-generation-for-ballerina-d6b8b8aaecd9?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6b8b8aaecd9</guid>
            <category><![CDATA[ballerina]]></category>
            <category><![CDATA[ballerina-installers]]></category>
            <category><![CDATA[installer-generation]]></category>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Mon, 03 Jan 2022 07:23:45 GMT</pubDate>
            <atom:updated>2022-02-02T06:30:58.815Z</atom:updated>
            <content:encoded><![CDATA[<p>Users can use ballerina language in their machine by building the ballerina distribution and publish it to maven central. However users can generate a Ballerina installer as well for their machine according to the Operating System they are using. Following steps will guide you to generate a ballerina installer for specific operating systems.</p><h3><strong>Build Ballerina Distribution</strong></h3><ol><li>Clone the repository using the following command</li></ol><pre>git clone <a href="https://github.com/ballerina-platform/ballerina-distribution">https://github.com/ballerina-platform/ballerina-distribution</a>.git</pre><p>2. This repository depends on github packages and you need to have a Personal Access Token (PAT) with read package permissions. Then you need to set the following environment variables in your terminal.</p><p><strong>Linux/Unix</strong></p><pre>export packageUser=&lt;Your github username&gt;</pre><pre>export packagePAT=&lt;Your personal access token&gt;</pre><p><strong>Windows</strong></p><pre>set packageUser=&lt;Your github username&gt;</pre><pre>set packagePAT=&lt;Your personal access token&gt;</pre><p>3. Run gradle build command as follows.</p><p><strong>Linux/Unix</strong></p><p>./gradlew build or ./gradlew clean build</p><p><strong>Windows</strong></p><p>.\gradlew.bat build or .\gradlew.bat clean build</p><p>This will create ballerina zip distributions in the ballerina/build/distributions directory. The content of the directory folder is as follows</p><pre>ballerina-&lt;version&gt;-SNAPSHOT.zip</pre><pre>ballerina-&lt;version&gt;-SNAPSHOT-swan-lake.zip</pre><pre>ballerina-&lt;version&gt;-SNAPSHOT-swan-lake-linux.zip</pre><pre>ballerina-&lt;version&gt;-SNAPSHOT-swan-lake-macos.zip</pre><pre>ballerina-&lt;version&gt;-SNAPSHOT-swan-lake-windows.zip</pre><h3><strong>Generate Ballerina Installers</strong></h3><p>After building the ballerina zip distributions, users can generate ballerina installers according to the operating system they use.</p><h4><strong>1. Linux/Ubuntu — deb Installer</strong></h4><p>Go to the installers/linux-deb directory and run the following command.</p><pre>./build-ballerina-linux-deb-x64.sh -v &lt;version&gt; -p &lt;path to folder which contains ballerina-&lt;version&gt;-SNAPSHOT-swan-lake-linux.zip&gt;</pre><p>eg:</p><pre>./build-ballerina-linux-deb-x64.sh -v 2201.0.0-SNAPSHOT-swan-lake -p ./../../ballerina/build/distributions</pre><p>Ballerina deb installer will be created in the installers/linux-deb/target directory as ballerina-&lt;version&gt;-swan-lake-linux-x64.deb.</p><h4>2. Linux/Centos — rpm installer</h4><p>Go to the installers/linux-rpm directory and run the following command.</p><pre>./build-ballerina-linux-rpm-x64.sh -v &lt;version&gt; -p &lt;path to folder which contains ballerina-&lt;version&gt;-SNAPSHOT-swan-lake-linux.zip&gt;</pre><p>eg:</p><pre>./build-ballerina-linux-rpm-x64.sh -v 2201.0.0-SNAPSHOT-swan-lake -p ./../../ballerina/build/distributions</pre><p>Ballerina rpm installer will be created in the installers/linux-rpm/rpmbuild/RPMS/x86_64 directory as ballerina-&lt;version&gt;-swan-lake-linux-x64.rpm.</p><h4>3. MacOS — pkg installer</h4><p>Go to the installers/mac directory and run the following command.</p><pre>./build-ballerina-macos-x64.sh -v &lt;version&gt; -p &lt;path to folder which contains ballerina-&lt;version&gt;-SNAPSHOT-swan-lake-macos.zip&gt;</pre><p>eg:</p><pre>./build-ballerina-macos-x64.sh -v 2201.0.0-SNAPSHOT-swan-lake -p ./../../ballerina/build/distributions</pre><p>Ballerina pkg installer will be created in the installers/mac/target/pkg directory as ballerina-&lt;version&gt;-swan-lake-macos-x64.pkg.</p><h4>4. Windows — msi installer</h4><p>You need dependency tools to generate windows msi installer for ballerina.</p><p><strong>Requirements</strong></p><ol><li><a href="https://wixtoolset.org/">Wix Toolset</a></li><li>GUID Generator — You can install dotnet guid generator by running the following command.</li></ol><pre>dotnet tool install -g dotnet-guid</pre><p>After installing the dependency tools, Go to the installers/windows directory and run the following command.</p><pre>.\build-ballerina-windows-x64.bat —-version &lt;version&gt; —-path &lt;path to folder which contains ballerina-&lt;version&gt;-SNAPSHOT-swan-lake-windows.zip&gt;</pre><p>eg:</p><pre>.\build-ballerina-windows-x64.bat  —-version 2201.0.0-SNAPSHOT-swan-lake —-path .\..\..\ballerina\build\distributions</pre><p>Ballerina msi installer will be created in the installers\windows\target\msi directory as ballerina-&lt;version&gt;-swan-lake-macos-x64.msi.</p><p>Users can use a different version of ballerina zip distributions as well which are already built. You need only to specify the version and the path to the ballerina zip distributions folder.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6b8b8aaecd9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java Management Extensions (JMX)]]></title>
            <link>https://nipunamadhushan96.medium.com/java-management-extensions-jmx-11f09b0e56bd?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/11f09b0e56bd</guid>
            <category><![CDATA[management-extensions]]></category>
            <category><![CDATA[mbean]]></category>
            <category><![CDATA[jmx]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Sun, 22 Nov 2020 20:13:06 GMT</pubDate>
            <atom:updated>2020-11-22T20:13:06.367Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is JMX ?</strong></p><p>Java Management Extensions(JMX) is the standard recommended way of managing and monitoring anything with java enabled. It’s a part of core Java SE since Java 5. It is an API, an architecture and a specification or a standard. There are two main JSRs and they are JSR 3 (original JMX) and JSR 160 (Remote JMX). JMX is very lightweight and you do not need MIBs or understand SNMP or require any proprietary software and just Java SE will do those work.</p><p><strong>What you can do with JMX</strong></p><p>Most of the java-based devices and applications need monitoring and management. JMX is the recommended way of doing this monitoring and managing. A very trivial application like “Hello World” is also needed to be monitoring and managing. Typically a Java application has business logic which implements the application’s functionality. But any non-trivial application also needs to be monitored, started and stopped, have configuration changed dynamically, monitored for performance and faults, etc.</p><p>JMX can also be the cornerstone of your application and all your services can themselves be MBeans leading to a highly modular, pluggable design. They manage resources like your server, OS, virtual machine or whatever you are managing are MBeans. The services like security, transactions also can be implemented as Mbeans. For a highly modular pluggable design, you can keep whatever the services you want and you can deactivate the ones you are not interested in just like removing. It’s also easy to replace some other service.</p><p><strong>Comparison of JMX with other technologies</strong></p><p>Whenever management client running remotely and management resources are running somewhere else, you need some remote technology to connect the tool. RMI, CORBA, SOAP and other IPC(Inter-Process Communication) technologies can be used to connect the tool.</p><p>EJB (Business Logic) — EJB implements the business logic but it has to be managed (life cycle management) inside the application server. EJBs can be managed with JMX.</p><p>Jini and JNDI — They are typically used for discovery. The remote client wants to discover the agent to talk and then a URL can be specified.</p><p>RMI — RMI can be used for remote connection from the management client to the JMX agent. It’s a lower-level technology.</p><p>Web Services — It’s another technology that could be used to connect JMX clients to agents.</p><p>JMS — It can be used for sending events from JMX agents to remote clients. A JMS queue or other resource from JMX also can be managed.</p><p><strong>Comparison of JMX with SNMP</strong></p><p>SNMP(Simple Network Management Protocol) is the de facto standard for network management of switches, routers, etc. However, if Someone wants to do more than network management (a combination of hardware and application management), JMX may be a better fit to do the task. SNMP exposes the management interface through a static MIB (Management Interface Base) while JMX relies on introspection of the Mbean Java classes for the interface. Structural changes to the agent are not visible to the SNMP client but in JMX with certain kinds of Mbeans,if you make structural changes in the agent, those could be visible to the remote client. Both SNMP and JMX support events through the traps and notifications. JMX can support richer data types than SNMP. A special tool kit is needed to implement the agent for the defined MIB in SNMP.</p><p><strong>JMX Architecture</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*W_eyMkAfFh_RoG_bIaPQbg.png" /><figcaption>JMX Architecture</figcaption></figure><p>JMX architecture has three main levels.</p><p>1. Probe Level (Instrumentation Level) — contains the probes(MBeans) instrumenting resources</p><p>2. Agent Level (Mbean Server) — the core of JMX. It acts as an intermediary between Mbeans and Applications.</p><p>3. Remote Management Level — enables remote applications to access the Mbean server through connectors and adaptors. A connector provides full remote access to MBeanServer API using various communication (RMI, IIOP, JMS, WS- …), while an adaptor adapts the API to another protocol (SNMP, …) or to Web-based GUI (HTML/HTTP, WML/HTTP, …). Java comes with the RMI connector.</p><p>Applications can be generic consoles(such as Jconsole and MC4j) or domain-specific(monitoring) applications.</p><p><strong>Probe/Instrumentation Level</strong></p><p>MBean is the fundamental entity in the instrumentation level. Functionality/resource you want to manage is exposed through a managed bean (MBean) that confirms to the JMX specification. An MBean has named and typed attributes (read and/or write), named and typed operations that can be invoked and notifications it can limit.</p><p>There are several kinds of Mbeans.</p><p>• Standard Mbean</p><p>• Dynamic Mbean</p><p>• Model Mbean</p><p>• Mxbean</p><p>• Open Mbean</p><p><strong>Standard MBeans and MxBeans</strong></p><p>A standard Mbean is defined by writing a java interface called SomethingMbean and a Java class called Something that implements that interface and provides the functionality of the instrumented resource. Every method in the interface defines either an attribute (get, set, …) or an operation(clear, …) in the Mbean. Operations can take arguments. In an attribute, you can return user-defined types as well. If you are doing that with Standard Mbean, the client needs to be aware of that class (Structure of the class). By default, every method defines an operation. Attributes and operations are methods that follow certain design patterns. A standard Mbean is composed of a Mbean interface and a class.</p><p>Java 6 allows you to create your own Mbeans. They are called MxBeans and you can define your user-defined classes. The remote client does not need to know about them as long as your custom class follows some basic rules. It basically needs to be converted and the framework should be able to convert your custom class into one of the standard types (Open types) as defined in the “java.management.openbean” package. The custom type class can either specify @ConstructorProperties annotation or add a static form (CompositeData) to reconstruct the custom type instance from an Open type (usually CompositeData) instance.</p><p><strong>Notifications</strong></p><p>To generate notifications, an MBean must implement the interface NotificationEmitter or extend NotificationBroadcasterSupport. To send a notification, you need to construct an instance of the class javax.management.Notification or a subclass (such as AttributeChangedNotification) and pass the instance to NotificationBroadcasterSupport.sendNotification . To receive a notification, a client has a notification handler which implements the NotificationListener (which has one method: handleNotification) which listens for specific notifications from Mbeans. The handler will get notifications emitted by the Mbeans which it is listening. Good design practice is to add a Notification hub that clients listen.</p><p><strong>Agent Level</strong></p><p>The central component of the agent level is the Mbean Server which is a registry of Mbeans and describes the management interface of each MBean. The MBean Server isolates the managed resources(Mbeans) from the management client therefore all operations go through the Mbean Server. ObjectName is used to register an MBean with the Mbean Server and clients use the ObjectName to get a reference to a Mbean. ObjectName is unique within an Mbean Server and it is of the form {DomainName]:property=value,[property=value]* .</p><p>Agent Level also has a set of agent services which are themselves registered as Mbeans with the Mbean Server. Standard mandatory services are M-let, Timer, Monitoring, Relation, etc.</p><p><strong>Remote Management Level</strong></p><p>Protocol connectors and/or adaptors allow remote management clients to access the managed resources. In the case of connectors, a specific transport protocol (e.g: RMI) is used to connect the client piece of the connector(on the management side) to the server piece of the connector(on the agent side). The management application understands JMX and accesses the Mbeans via a remote interface to the Mbean Server. In the case of protocol adaptors, the management application is connecting to a protocol adaptor that adapts/maps the Mbean interface into a different protocol’s interface (e.g: SNMP adaptor, HTTP adaptor, Web services adaptor). The advantage is that is this case the management application does not need to understand JMX or even Java.</p><p><strong>How to manage a resource with JMX</strong></p><p>First of all, a resource (application, device, service, etc) should be selected that has been developed in Java or has a Java wrapper. Then functionality you want to manage through a Mbean that conforms to the JMX specification should be exposed. An MBean has named and typed attributes (read and/or write), named and typed operations that can be invoked and notifications that it can emit. Then your Mbeans should be registered with a Mbean Server that is part of a JMX agent. Then Mbeans are accessed through the connectors or protocol adaptors remotely to manage the resource from your management client.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11f09b0e56bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Allocation in Java]]></title>
            <link>https://nipunamadhushan96.medium.com/memory-allocation-in-java-d50826f15d73?source=rss-b7586b019f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d50826f15d73</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[threading]]></category>
            <category><![CDATA[heapdump]]></category>
            <category><![CDATA[threaddump]]></category>
            <dc:creator><![CDATA[Nipuna Madhushan]]></dc:creator>
            <pubDate>Thu, 18 Jul 2019 04:38:49 GMT</pubDate>
            <atom:updated>2019-07-18T04:38:49.617Z</atom:updated>
            <content:encoded><![CDATA[<p>To execute an application in an optimal way, Java Virtual Machine (JVM) divides the memory into two main memory spaces and they are stack memory and heap memory. There are some other memory allocations also in the JVM and they are Perm Gen, Native Memory and PC-Registers. The JVM designates memory for operations such as declaring new variables and objects, methods, declaring strings in the stack memory or in the heap space. Let’s go more specifically through these memory models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*aSWE5xh7_OOM4QuP898yhw.png" /><figcaption>Memory Allocation in a Java Program</figcaption></figure><p><strong>Stack Memory in Java</strong></p><p>Stack Memory in java is used for static memory allocation and the execution of a thread. It contains primitive values that are specific to a method and references to objects that are in a heap, referenced from the method. Stack stores the data which have a short life time such as local variables.</p><p>Access to this memory is in Last-in First-out(LIFO) order. Whenever a new method is called, a new block on the top of the stack is created which contains the values specific to that method. We call it a Stack Frame. When a method is called inside of another method, another new block on the top of the stack is created. After method finishes the execution, its corresponding stack frame is flushed and the flow goes back to the calling method. Then the space becomes available for the next method.</p><p>In a java program each thread has its own stack. Therefore you can see that multi-threading can decrease the time taken for execution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*LG6XAA34Ng191ChTPqzawQ.png" /><figcaption>Execution of a Stack</figcaption></figure><p>Some of the key features of Stack Memory are mentioned below.</p><ul><li>Stack Memory grows and shrinks as new methods are called and returned respectively.</li><li>Variables inside stack exist only as long as the method that created them is running.</li><li>It’s automatically allocated and deallocated when method finishes the execution.</li><li>If this memory is full, java throws <em>java.lang.StackOverFlowError</em></li><li>Access to this memory is fast when compared to heap memory.</li><li>Stack memory is threadsafe as each thread operates in its own stack.</li></ul><p>Stack memory only exists as long as the current method is running and comparatively much faster to allocate.</p><p><strong>Heap Space</strong></p><p>Heap Space(Heap Memory) in java is used for dynamic memory allocation for java objects and JRE classes at the runtime. New objects are always created in heap space and the references to this objects are stored in stack memory. These objects have global access and can be accessed from anywhere in the application. Heap Space stores the data which have a long lifetime. There is only one heap space for all the threads. Most objects are quite big and most programs want to pass around objects between blocks of codes. By placing objects in heap, it makes easy to pass them around and all threads and stacks can access them in the heap.</p><p>This memory model is divided into smaller parts called generations.</p><ol><li><strong>Young Generation — </strong>where all new projects are allocated and aged. A minor garbage collection occurs when this fills up.</li><li><strong>Old(Tenured) Generation </strong>— where long surviving objects are stored. When objects are stored in the Young Generation, a threshold for the object’s age is set and when that threshold is reached, object is moved to old generation.</li><li><strong>Permanent Generation </strong>— consists of JVM metadata for the runtime classes and application methods.</li></ol><p>Young Generation is also divided into another three small parts.</p><ol><li>Eden Space — Where all the new objects are stored</li><li>Survivor Space 0 — Where the objects are stored after the action of garbage collection in the Eden Space</li><li>Survivor Space 1 — Where the objects are stored after the action of garbage collection in the Survivor Space 0</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ir0VtSskyzhoLBAfdNlnMg.png" /><figcaption>Heap Memory Space</figcaption></figure><p>Some key features of heap memory are mentioned below.</p><ul><li>it’s accessed via complex memory management techniques that include Young Generation, Old Generation and Permanent Generation.</li><li>If heap space is full, java throws <em>java.lang.OutOfMemoryError</em></li><li>Access to the memory is relatively slower than stack memory.</li><li>This memory isn’t automatically deallocated. It needs Garbage Collector to free up unused objects so as to keep the efficiency of the memory usage.</li><li>Unlike stack, a heap isn’t threadsafe and needs to be guarded by properly synchronizing the code.</li></ul><p>Heap Space exists as long as the application runs and slower to allocate compared to stack.</p><p><strong>Garbage Collector</strong></p><p>When the Young Generation filled up, the Garbage Collector come in and this type of garbage collection is called Minor Garbage Collection (Minor GC). Objects which goes through different life cycles and a lot life cycles in garbage collection but still survived, will be moved into the Old Generation where the long living objects are stored. The Garbage Collection which happens in the Old Generation is called Major Garbage Collection (Major GC). This helps to identify the objects which are in the old generation not helpful anymore. All the new objects are stored in Eden Space and objects survived from the Minor GC are moved the Survivor Space 0. Minor Garbage Collector also checks the Survivor Space and the objects survived are moved into the other Survivor Space. Therefore it can make sure that the Survivor Space is always empty. Objects which are survived a lot of cycles will be moved into the Old Generation like I have mentioned earlier. It’s done by setting a threshold for the age of the young generation objects before they become eligible to promote for the old generation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*c4XenZDVB39NanwtCKV8YA.png" /><figcaption>Actions of Garbage Collectors inside a Heap</figcaption></figure><p>Different Steps inside a Garbage Collection</p><ol><li>Marking — Garbage Collection identifies which are the objects not in use</li><li>Normal Deletion — unused objects will be removed from the heap</li><li>Deletion + Compacting — Once objects are removed from the heap, memory allocation is random. These memory allocations are grouped together so that the memory allocation in the future will be faster. (As a part of deleting objects from the heap, compacting help as grouping the memory together so that the performance of the creation or the allocation of new memory increased in the subsequent calls.)</li></ol><p>Different types of Garbage Collection</p><ul><li>Serial GC — This is useful when we need to mark and delete simply in the young and old generations. This is used in small applications which have low memory foot prints because it’s directly going to arrange by the objects and then delete them from the heap. This might not be a solution for large scale applications when you have a lot of threads running on the heap.</li><li>Parallel GC — Most of the features are the same as Serial Gcs but they can spawn N number of threads for the young generation and N number of threads are based on the CPU which are present in the system. We can control this number of threads by setting up some parameters when we start the JVM. These are also called as the throughput collectors because it uses multiple CPUs and it speeds up the garbage collection performance. It uses only one thread for the old generation since there is less chance to be garbage collected in the old generation.</li><li>Parallel Old GC — This is actually the same as the Parallel GC except the point that old generation also have N number of threads.</li><li>Concurrent Mark Sweep(CMS) GC — This is also refereed to us as concurrent low cost collectors. It does the garbage collection for old generation only. These collectors try to minimize the pause happen during the garbage collection. We can limit the number of threads in the CMS collector by using some JVM options as well. This is useful if we do not want to pass an application for a long period.</li><li>Garbage First(G1) GC — It is a parallel concurrent and incrementally compacting low cost garbage collector. There is no concept like young and old generations space. It divides the heap space into multiple equally sized heaped regions and whenever there is a garbage collection involved, it collects the region first with the lesser live data (Garbage First).</li></ul><p><strong>Native Memory</strong></p><p>Native Memory is where all our other language specific codes reside. As an example shocket connections reside in the native memory behalf of residing in the stack or heap memory.</p><p><strong>Perm Gen(Method Area)</strong></p><p>Perm Gen is the space where the compiled objects of methods and classes are stored. They are a part of the heap memory and then it can occur the Out of Memory Error. But different memory sizes can be provided for the JVM. Therefore they have the classes got loaded as a part of the class loader. Perm Gen was replaced with the Metaspace with the Java8.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*iLkCA9pKkHcssOXbI43Wgw.png" /><figcaption>Replacement of Perm Gen by Metaspace</figcaption></figure><p><strong>Metaspace</strong></p><p>Metaspace are a part of native memory unlike the perm gen which has a memory inside the heap. These are at the process level and they do not merge inside the heap memory. Therefore Metaspaces can be given separate spaces that does not merge with the heap memory. Process sizes can go large since the metaspace goes to the OS and then it will not occur the Out of Memory Error. But too many classes loading on the OS will run out of memory in the OS and it can bring down the hole server.</p><p><strong>PC Registers</strong></p><p>PC Registers store the sequence of information/instruction which needs to be executed next. There is one PC register per thread. It tells the thread what it needs to do next.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d50826f15d73" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>