How to Use Distlang JS Client: Record Counters & Histograms
Recording application metrics from serverless and edge environments is fundamentally different from doing so on a traditional server. There’s no long-running process to scrape. There’s no sidecar to collect data. The handler runs, responds, and dies. If you didn’t push your data out before termination, it’s gone.
This guide covers how to use the Distlang JS client to record counters and histograms in these short-lived environments. Every term and concept maps to a concrete workflow: install, define, record, flush, view.
Get started with the quickstart to follow along with code as you read.
Why Push-Model Metrics Exist
Before getting into the client itself, it helps to understand why a tool like this is necessary.
Prometheus, the dominant open-source metrics system, works by polling (scraping) your service endpoints on a schedule. That model assumes your application is running continuously at a known address. As one practitioner on DEV Community put it bluntly: “Prometheus can’t support serverless. Prometheus works by polling your service endpoints… that works for virtual machines. It does not work for ECS Fargate, and definitely does not work for AWS Lambda.”
Prometheus developers themselves have acknowledged this gap, noting that short-lived FaaS workloads push users toward a push model because there’s nothing stable to scrape.
Edge environments make this worse. They use lean runtimes without full Node.js support. Vercel limits request sizes to 1MB and function bundles to 4MB. There are no TCP or UDP connections available. Traditional StatsD-over-UDP or Prometheus scrape patterns are physically impossible in these runtimes.
The Distlang JS client is purpose-built for these constraints. It buffers metric recordings in memory during request handling, then pushes them over HTTP to the Distlang Metrics API before the isolate terminates. No agents, no scrape endpoints, no infrastructure to manage.
For more background on serverless architecture and observability, that guide covers the broader context.
Installing and Initializing the JS Client
The @distlang/client package is the npm package you install to instrument your application. It’s lightweight by design, built for edge and serverless runtimes where bundle size and cold start time matter.
npm install @distlang/client
After installation, you initialize the client by creating a metric set. A metric set is a Distlang-specific concept: a named group of counters and histograms declared together. The hosted dashboard auto-generates one dashboard per metric set, so the name you choose here becomes your dashboard name.
import { MetricSet } from "@distlang/client";
const metrics = new MetricSet({
name: "my-api",
apiToken: env.DISTLANG_API_TOKEN,
});
The API token is a single long-lived bearer token that authenticates your client to the Distlang Metrics API. You generate it at dash.distlang.com, and one token covers your entire account. This avoids the multi-key sprawl that plagues larger observability setups. See the API tokens documentation for setup details.
The full JS client documentation covers all initialization options.
Recording Counters
A counter is a cumulative metric that only goes up. The Prometheus project defines it as “a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on restart.” In practice, counters track events that happen repeatedly: requests served, errors occurred, sign-ups completed, jobs processed.
In Distlang, recording a counter looks like this:
metrics.counter("requests_total", 1, { status: response.status });
Three arguments: the metric name, the increment value, and an optional labels object.
The key difference from Prometheus counters is conceptual. In a traditional setup, a counter lives in process memory and gets scraped periodically. In Distlang, a counter observation is recorded, buffered in the client, and pushed over HTTP on flush. There’s no “reset on restart” to worry about because there’s no long-running process. Each isolate invocation records its observations independently.
When to use counters
Use counters when you need a reliable, ever-increasing total. Good candidates:
requests_total— total request count, sliced by status code or routeerrors_total— error count, sliced by error typesignups_total— business events that matter for product analyticscache_hits_total— operational metrics for performance tuning
Counters answer the question “how much has happened?” If you need to know how values are distributed (how long requests take, how large payloads are), you want a histogram instead.
For a deeper walkthrough of instrumenting counters and histograms in JavaScript, that guide covers additional patterns.
Recording Histograms
A histogram records observations and sorts them into configurable buckets to show value distributions. Instead of just giving you an average (which can be misleading), a histogram shows how often values fall within certain ranges. It also tracks the total sum of all observed values and the total count of observations.
In the Distlang JS client, recording a histogram looks like this:
const start = Date.now();
// ... handle request ...
metrics.histogram("request_duration_ms", Date.now() - start);
This records a single observation, the request duration in milliseconds, into the request_duration_ms histogram.
Why histograms matter for serverless
Histograms are aggregatable across distributed systems. This is particularly important for serverless workloads where data comes from many ephemeral isolates running in parallel. You can’t aggregate percentiles from summaries across multiple sources, but you can aggregate histogram buckets. This makes histograms the right choice for distributed latency tracking.
When to use histograms
request_duration_ms— how long requests takepayload_size_bytes— response or request body sizesupstream_latency_ms— time spent waiting on external APIsqueue_wait_ms— time items spend in a queue before processing
Histograms answer the question “how are values distributed?” If you just need to count events, use a counter.
A practical heuristic: counters tell you how much has happened, histograms tell you how those things are shaped. The article on serverless counters and histograms for edge functions goes deeper on choosing between the two.
Flushing Metrics Before the Isolate Dies
Flush is not an implementation detail in serverless. It’s existential. If you don’t flush before the isolate terminates, your buffered metric data is gone permanently.
Every metrics, analytics, or telemetry client running inside a Cloudflare Worker or Vercel function faces the same fundamental problem: the handler is short-lived, and buffered data must be sent before the isolate dies.
The core pattern for how to use the Distlang JS client to record counters and histograms in production is: record during the request, flush after the response.
Cloudflare Workers: ctx.waitUntil
export default {
async fetch(request, env, ctx) {
const start = Date.now();
const response = await handleRequest(request);
metrics.counter("requests_total", 1, { status: response.status });
metrics.histogram("request_duration_ms", Date.now() - start);
ctx.waitUntil(metrics.flush());
return response;
},
};
ctx.waitUntil() tells the Workers runtime to keep the isolate alive until the flush promise resolves, even though the response has already been sent to the client. This is the standard pattern for instrumenting Cloudflare Workers with any async post-response work.
Vercel / Next.js: after()
import { after } from "next/server";
export async function GET(request) {
const start = Date.now();
const data = await fetchData();
metrics.counter("api_calls_total", 1, { route: "/api/data" });
metrics.histogram("fetch_duration_ms", Date.now() - start);
after(() => metrics.flush());
return Response.json(data);
}
The after() function in Vercel serves the same purpose as ctx.waitUntil(): it runs code after the response without blocking it. See the guide on using after() in Vercel for edge function metrics flush patterns.
The buffering tradeoff
The details of how your client buffers and flushes matter enormously. Too much batching and you lose data when the isolate terminates. Too little and you’re making excessive network calls that add latency and cost.
This is a real problem across the ecosystem. PostHog’s Cloudflare Workers integration recommends setting flushAt to 1 and flushInterval to 0 to avoid batching-related data loss in ephemeral environments. LaunchDarkly’s documentation explicitly says you must flush inside waitUntil or events won’t reach their servers.
The Distlang JS client handles this with configurable buffering and flush behavior tuned for short-lived handlers.
Labels and Dimensional Metrics
Labels are key-value pairs attached to a metric that enable dimensional slicing and filtering. When you pass { status: 200 } as the third argument to metrics.counter(), you’re adding a label.
metrics.counter("requests_total", 1, { status: response.status });
metrics.counter("requests_total", 1, { status: response.status, route: "/api/checkout" });
Labels turn a single metric name into a multidimensional dataset. You can filter by status code, group by route, or aggregate across regions. They’re fundamental to useful dashboards.
Good label examples:
{ status: 200 }— HTTP status code{ route: "/api/checkout" }— request path{ region: "us-east" }— deployment region{ method: "POST" }— HTTP method
Cardinality: Why Label Discipline Matters
Cardinality is the number of unique label combinations for a metric. Every distinct combination creates a separate time series, and each time series generates rows in your metrics storage.
High-label cardinality means many unique combinations. This increases memory use, CPU use, query times, and storage requirements. On metered plans, it directly impacts cost. On Distlang’s row-based pricing (500k rows/month free, scaling to 20M at $79/mo), every unique label combination counts against your allocation.
Compare Distlang plan features to understand how row limits map to your expected cardinality.
What to avoid
Never use high-cardinality values as labels:
- User IDs (millions of unique values)
- Request IDs (unique per request)
- Timestamps (infinite cardinality)
- Full URLs with query parameters
What works
Stick to bounded, low-cardinality values:
- HTTP methods (GET, POST, PUT, DELETE)
- Status code buckets (2xx, 4xx, 5xx) or exact codes (200, 404, 500)
- Route patterns (“/api/users”, “/api/orders”)
- Boolean flags (cached: true/false)
Best practices include using a consistent naming convention for self-explanatory label keys, keeping label values short and bounded, and planning your label schema before you ship. The guide on label naming and cardinality strategies covers this in detail.
The Hosted Dashboard
Once you flush metrics, they appear on the hosted dashboard at dash.distlang.com. Each metric set automatically gets its own dashboard, no Grafana or Prometheus setup required.
The dashboard includes AI chart suggestions: chart titles and descriptions are generated automatically from your incoming metrics. This means you get a usable dashboard with near-zero manual configuration. For teams that need to understand their data quickly without spending time on chart design, this removes a real friction point.
Cloudflare provides built-in platform metrics like request counts, error rates, CPU time, and execution duration. But those are platform-level numbers. Custom application metrics (business events, route-specific latencies, feature flag usage) require instrumentation from your code, which is exactly what the Distlang JS client provides.
The Metrics API for Non-JS Stacks
The Distlang Metrics API is the HTTP endpoint that receives metric data. While the JS client is the primary interface for JavaScript developers, the raw API with bearer token authentication means any language or platform can send metrics over HTTP.
This matters if you have polyglot services or want to send metrics from a Python backend, a Go service, or even a shell script in CI. The API accepts the same counter and histogram data that the JS client sends.
Putting It All Together
The complete workflow for how to use the Distlang JS client to record counters and histograms looks like this:
- Install the
@distlang/clientpackage - Initialize a metric set with your API token
- Record counters for event counts and histograms for value distributions
- Flush before the isolate terminates using
ctx.waitUntil()orafter() - View your data on the auto-generated dashboard at dash.distlang.com
That’s the full loop. No agents to deploy, no time-series databases to manage, no Grafana dashboards to build by hand.
For a complete walkthrough with working code, the end-to-end example takes you from application code to a live dashboard in minutes.
Start with the metrics quickstart to get your first counters and histograms recording today.
Frequently Asked Questions
What is the difference between a counter and a histogram in Distlang?
A counter tracks events that only increase: total requests, total errors, total sign-ups. A histogram tracks the distribution of values: how long requests take, how large payloads are. Use counters for “how many” questions and histograms for “how fast” or “how big” questions.
Do I need to run Prometheus or Grafana to use Distlang?
No. Distlang is an API-first metrics service. The JS client pushes data directly to the Distlang Metrics API, and dashboards are auto-generated at dash.distlang.com. There’s no scrape endpoint to configure, no TSDB to maintain, and no dashboard tool to set up.
What happens if I forget to flush?
Your metric data is lost. In serverless environments, the isolate terminates after the response is sent. Any data still buffered in the client disappears with it. Always call ctx.waitUntil(metrics.flush()) on Cloudflare Workers or after(() => metrics.flush()) on Vercel.
How does label cardinality affect my Distlang bill?
Every unique combination of label values creates a separate time series, and each observation generates rows counted against your monthly plan limit. High-cardinality labels like user IDs or request IDs can burn through your row allocation quickly. Stick to bounded values like HTTP methods, status codes, and route patterns.
Can I use the Distlang Metrics API without the JS client?
Yes. The Metrics API accepts HTTP requests with bearer token authentication. Any language or tool that can make HTTP POST requests can send counter and histogram data. The JS client is a convenience wrapper that handles buffering and flushing, but the API is the underlying protocol.
Why can’t I use Prometheus client_js in Cloudflare Workers?
Prometheus client_js assumes a long-running Node.js process that exposes an HTTP endpoint for scraping. Cloudflare Workers are short-lived isolates with no persistent process and no inbound scrape endpoint. Edge runtimes also lack full Node.js APIs, so many Prometheus client dependencies won’t work at all.
How many rows does the free plan include?
The free plan at Distlang includes 500k rows per month with 7-day retention and unlimited metric sets. AI chart suggestions are included at every tier.
Does Distlang work with Vercel and Cloudflare Workers?
Yes. Distlang provides quickstart guides for both platforms. On Cloudflare Workers, you flush with ctx.waitUntil(). On Vercel and Next.js, you flush with after(). Both patterns ensure metrics are sent after the response without blocking it.