How to Log Proxy Traffic Usage in Your Backend
Know where your proxy traffic goes. Learn which fields to log, how to count bytes, how to store and summarise usage, and how to keep the logs private.
9 min readUpdated Nov 13, 2026By XPASS Editorial Team

Proxy traffic is easy to ignore until the day it matters. A job starts retrying, a developer leaves a debug loop running, or a customer feature turns out to move far more data than anyone planned, and suddenly nobody can say where the traffic went. The proxy provider can tell you the account total, but only your own backend knows which job, which customer, which endpoint and which target a request belonged to. This guide shows how to record proxy usage in your own system in a way that is simple, light to run, private and useful: what to capture, how to count bytes honestly, how to store and summarise the data, and how to turn it into alerts. Use proxies only for lawful work and follow the terms of the services you call.
Why keep your own usage log
There are four practical reasons.
- Attribution. Totals from a provider dashboard do not tell you which project or customer used them. Your log can.
- Early warning. If your plan has a traffic or connection allowance, you want a warning well before it runs out, not after requests start to fail. Check the plan page for how usage is counted.
- Debugging. When a target starts returning errors, a per-request history shows when it began, which endpoint was involved and whether retries made it worse.
- Planning. Weekly trends tell you whether next month needs more headroom, or whether a wasteful job should be fixed first.
A usage log is not surveillance of your users. Its job is to describe your own system's traffic, so keep it narrow and avoid collecting anything that is not needed for those four purposes.

What to record for each request
Decide the fields once and keep them consistent. A good minimal set:
| Field | Why it helps |
|---|---|
ts |
When the request started; store in UTC |
job_id or project |
Which job, feature or customer plan the request belongs to |
endpoint_id |
A label for the proxy endpoint used, never a URL with credentials |
target_host |
Host name only, such as api.example.com |
method |
GET, POST and so on |
path_group |
A cleaned or templated path such as /v1/orders/:id, without identifiers or query strings |
status |
HTTP status, or a short error code such as ETIMEDOUT |
attempt |
1 for the first try, 2 or more for retries |
duration_ms |
Total elapsed time for the attempt |
bytes_out / bytes_in |
Request and response size, see the next section |
outcome |
success, client_error, server_error, proxy_error, timeout |
The attempt field is especially valuable. Retries are a hidden multiplier of traffic, and being able to separate first attempts from repeats shows you how much of your usage is waste. The design of those retries is covered in handling retry and timeout with a proxy.
Counting bytes honestly
Bytes are the part that surprises people, because there are several things you could mean.
- Payload bytes. The size of request and response bodies. Often available from
Content-Length, but that header can be missing or wrong with chunked or compressed responses. - Header bytes. Request and response lines and headers. They can be a surprising share for small API calls.
- Tunnel overhead. For HTTPS, the
CONNECTexchange and the TLS handshake and record framing add bytes that your application code never sees. - Compression. If the response is compressed on the wire, the transferred size is smaller than the decoded size your code reads.
The most reliable approach in application code is to count bytes as they stream: wrap the request body stream and the response stream with a small counter, and add the totals when the response ends. Fall back to Content-Length only when streaming is impractical. Document which definition you use so that the numbers mean the same thing next month. The semantics of message bodies and headers are defined in RFC 9110, and it helps to know the difference between the message and the transport.
Your count will almost certainly differ from the provider's, because the provider sees the wire. Treat your figure as a good estimate for trends and attribution, and reconcile against the provider's number with a tolerance, for example by checking that the two stay in a roughly constant ratio.
Where to put the logging code
Put it in one place, at the layer that every proxied request passes through: your HTTP client wrapper, an interceptor, or the dispatcher that picks the endpoint. Scattering log calls across business code leads to gaps.
A sketch for a fetch-style wrapper:
async function trackedFetch(url, options, ctx) {
const started = Date.now();
const u = new URL(url);
let status = null;
let outcome = "success";
let bytesIn = 0;
try {
const res = await ctx.doRequest(url, options);
status = res.status;
const body = await res.arrayBuffer();
bytesIn = body.byteLength;
if (status >= 500) outcome = "server_error";
else if (status >= 400) outcome = "client_error";
return new Response(body, { status: res.status, headers: res.headers });
} catch (err) {
outcome = err.name === "TimeoutError" ? "timeout" : "proxy_error";
status = err.code || err.name;
throw err;
} finally {
ctx.record({
ts: new Date(started).toISOString(),
job_id: ctx.jobId,
endpoint_id: ctx.endpointId,
target_host: u.host,
method: options?.method || "GET",
path_group: ctx.pathGroup(u.pathname),
status: String(status),
attempt: ctx.attempt,
duration_ms: Date.now() - started,
bytes_in: bytesIn,
bytes_out: Number(options?.body?.length || 0),
outcome,
});
}
}
The record function should not block the request. Push rows into an in-memory buffer and flush them in batches to your database or log pipeline, and make sure a logging failure can never break a business call. The endpoint selection that supplies endpointId is described in managing a connection pool across several proxy IPs.
Storing and summarising the data
For most teams a simple relational table is enough.
CREATE TABLE proxy_usage (
id BIGSERIAL PRIMARY KEY,
ts TIMESTAMPTZ NOT NULL,
job_id TEXT NOT NULL,
endpoint_id TEXT NOT NULL,
target_host TEXT NOT NULL,
method TEXT NOT NULL,
path_group TEXT,
status TEXT NOT NULL,
attempt INT NOT NULL DEFAULT 1,
duration_ms INT NOT NULL,
bytes_in BIGINT NOT NULL DEFAULT 0,
bytes_out BIGINT NOT NULL DEFAULT 0,
outcome TEXT NOT NULL
);
CREATE INDEX proxy_usage_ts_idx ON proxy_usage (ts);
CREATE INDEX proxy_usage_job_idx ON proxy_usage (job_id, ts);
Then build a daily summary, either with a scheduled query or a materialised view:
SELECT date_trunc('day', ts) AS day,
job_id,
count(*) AS requests,
count(*) FILTER (WHERE attempt > 1) AS retries,
sum(bytes_in + bytes_out) AS total_bytes,
count(*) FILTER (WHERE outcome <> 'success') AS failures
FROM proxy_usage
GROUP BY 1, 2
ORDER BY 1 DESC, total_bytes DESC;
Keep detailed rows for a short window and keep the daily summaries much longer. If volume grows, partition the table by day, or send events to a time-series or log system instead. The shape of the data stays the same.
A plain worked example
A team runs three jobs through proxies: a nightly report, a customer-facing lookup and an internal test script. They add the wrapper above and, within a week, they learn three things.
- The test script, which nobody remembered, produced about a third of the retries because it pointed at a staging host that rejected the proxy. They fix the config, and the retries disappear.
- The nightly report moves most of the bytes, but nearly all of them are response bodies of a few large endpoints that could be requested with filters. They change the query, and traffic falls.
- The lookup feature spikes every Monday morning. Knowing that, they raise its concurrency limit slightly before Monday and lower it afterwards.
They also add two alerts: one when the 24-hour byte total passes a chosen share of the allowance in their plan, and one when the failure ratio of any job exceeds a threshold for an hour. The numbers for the allowance come from the plan page, not from assumptions. They review how the traffic is spread across rotating addresses in building a bounded proxy rotation strategy.
Here is a short illustration with invented numbers. Suppose a nightly job makes 2,000 requests through a proxy. Your log shows an average of 180 KB per response and 3 KB per request, with 5 percent of requests retried once. The response volume is 2,000 x 180 KB, about 360 MB. Requests add about 6 MB. Retries add roughly 5 percent of that total, around 18 MB. The nightly estimate is therefore about 384 MB, and a month of such runs is close to 11.5 GB. If the provider's dashboard shows noticeably more than this, the gap is worth investigating: connection setup, redirects you did not log, or a second job using the same credentials are typical causes.
Privacy, security and retention
A traffic log can become a sensitive data set if you are careless.
- Never log secrets. No proxy passwords,
Authorizationheaders, cookies or API keys. Redact them in error messages too, since many HTTP libraries include the request config in exceptions. - Clean URLs. Log the host and a templated path. Drop query strings, which often hold tokens, e-mail addresses or identifiers.
- No bodies. Counting body size is enough. Do not store the body.
- Access control. Restrict who can read the table, and keep it out of public dashboards.
- Retention. Delete or aggregate detailed rows after the period you need. Follow your organisation's policy and local data protection law, and remember that IP addresses and user identifiers can be personal data.
Limits and what to watch for
- Estimates are not invoices. Your numbers help with trends and attribution but will not match the provider's exactly.
- Logging overhead. Per-request logging adds a little CPU and storage. Batch writes, and sample if the volume is extreme, but never sample failures.
- Clock and time zone drift. Store UTC and summarise per UTC day, then convert when displaying.
- Lost events. A crash can lose buffered rows. For billing-critical numbers, rely on the provider's figure and use yours for operations.
- Plan details. How connections, bandwidth or requests are counted depends on the plan. Read the plan page and match your summary to the same unit.
- Policy compliance. Usage logs do not make a risky job acceptable. Traffic must still follow the target's terms and the law.
A practical way to use the log is to define a reconciliation routine. Once a week, compare your total with the provider's figure for the same period and note the difference as a percentage. A small, stable gap is normal; a gap that suddenly widens points to something that changed, such as a new endpoint, a larger payload or traffic from an untracked system. Keep the percentage in a simple spreadsheet so that you notice trends early.
Summary
Log every proxied request at one central layer, with a small, consistent set of fields: time, job, endpoint label, target host, cleaned path, status, attempt, duration, bytes and outcome. Count bytes by streaming where you can, be clear about what your number includes, and expect it to differ from the provider's. Store detailed rows briefly in a simple indexed table, keep daily summaries longer, and use them for attribution, alerts and planning. Keep secrets, bodies and full URLs out of the log, and apply access control and retention rules. When you are ready to pick a proxy plan to monitor, see the XPASS proxy page.
Frequently asked questions
Why log proxy traffic in my own backend if the provider has a dashboard?
A provider dashboard shows totals for the account. Your own log shows which job, customer or feature produced the traffic, which targets were involved and which requests failed, and it lets you set alerts before a limit is reached.
Will my byte counts match the provider's numbers exactly?
Usually not exactly. Your code often sees payload bytes, while the provider may count headers, tunnel set-up and encryption overhead too. Use your log for trends and attribution and reconcile against the provider figure with a tolerance.
What should I never write to a traffic log?
Proxy passwords, authorization headers, cookies, request or response bodies and full URLs that contain tokens or personal data. Log the host and a cleaned path instead.
How long should usage logs be kept?
Keep detailed rows only as long as you need them for debugging, often days to a few weeks, and keep daily summaries longer. Follow your own retention policy and local data protection rules.
About the author

Bob Kanokphon Thongdee
- Founder of XPASS VPN
- Co-founder of eSIMonline.asia
- More than 7 years in online marketing
- Founder of Cojourney Visa and Cojourney Travel
Need a proxy for this?
XPASS Proxy sells residential proxy traffic by the gigabyte, with the price shown before you pay.
See proxy plansKeep reading

Proxy Guides
How to Manage a Connection Pool When Using Multiple Proxy IPs
When your code uses several proxy IPs, connection handling matters. See how to keep one pool per endpoint, cap concurrency, retire bad endpoints and avoid leaks.
10 min read

Proxy Guides
How to Build a Bounded Proxy Rotation Strategy
Rotation is easy to start and hard to control. This guide shows how to set limits on pool size, requests per IP and retries so a lawful workload stays predictable and easy to debug.
9 min read

Proxy Guides
How to Handle Retry and Timeout When Using a Proxy
Proxied requests have more places to fail. Learn how to set layered timeouts, choose which errors deserve a retry, add backoff and keep retries polite.
9 min read