Track cost per customer
Adding up session costs by customer lets you bill your own customers for what they use, or find the customers who cost the most. Tag each session with the customer's ID in metadata. After the session ends, read its cost from the API, and add the costs up by that ID. A session's cost uses your plan's rates, and on Launch and Scale, it counts browser time by the second, as your invoice does. See Pricing.
Before you begin
Put your Steel API key in the STEEL_API_KEY environment variable, and install the Steel SDK with npm install steel-sdk or with pip install steel-sdk in a virtual environment. In Go and Rust, each program is the main.go of a module or the src/main.rs of a Cargo project, set up as the Go and Rust SDK pages show.
1. Tag sessions with metadata
Add the customer's ID to metadata when you create the session. Metadata is a flat set of keys and values that Steel keeps with the session. You can filter the list of sessions by it, and the session viewer in the dashboard shows it.
This program creates a session for one customer, prints its metadata, and releases it.
import Steel from "steel-sdk";
const client = new Steel();
const session = await client.sessions.create({
metadata: { customer_id: "cus_1042", job_id: "job-7731" },
});
try {
console.log(session.id, session.metadata);
} finally {
await client.sessions.release(session.id);
}from steel import Steel
client = Steel()
session = client.sessions.create(
metadata={"customer_id": "cus_1042", "job_id": "job-7731"},
)
try:
print(session.id, session.metadata)
finally:
client.sessions.release(session.id)package main
import (
"context"
"fmt"
"log"
"github.com/steel-dev/sdk/go"
"github.com/steel-dev/sdk/go/shared"
)
func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
client := steel.NewClient()
session, err := client.Sessions.New(ctx, steel.SessionNewParams{
Metadata: steel.F(map[string]steel.SessionNewParamsMetadataUnion{
"customer_id": shared.UnionString("cus_1042"),
"job_id": shared.UnionString("job-7731"),
}),
})
if err != nil {
return err
}
defer func() {
if _, err := client.Sessions.Release(ctx, session.ID); err != nil {
log.Print(err)
}
}()
fmt.Println(session.ID, session.Metadata)
return nil
}#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = steel_rs::Client::new();
let session = client
.sessions()
.create(steel_rs::SessionCreateParams {
metadata: Some(std::collections::HashMap::from([
(
"customer_id".to_owned(),
steel_rs::SessionCreateParamsMetadata::String("cus_1042".to_owned()),
),
(
"job_id".to_owned(),
steel_rs::SessionCreateParamsMetadata::String("job-7731".to_owned()),
),
])),
..Default::default()
})
.await?;
let result: Result<(), Box<dyn std::error::Error>> = async {
println!("{} {:?}", session.id, session.metadata);
Ok(())
}
.await;
client.sessions().release(&session.id).await?;
result
}Run the program:
npx tsx tag.mtspython tag.pygo run .cargo runThe program prints the session's ID and metadata:
d06c61eb-8a3e-437c-bbb8-32b1648d2b1a { customer_id: 'cus_1042', job_id: 'job-7731' }72816a1f-ed17-457e-bb1e-fb874a432415 {'customer_id': 'cus_1042', 'job_id': 'job-7731'}ca3318c5-b0e8-4fe7-ae86-a7c1ae690f14 map[customer_id:cus_1042 job_id:job-7731]26060bd1-8a36-4069-bf10-9a16719fee0d Some({"customer_id": "cus_1042", "job_id": "job-7731"})Use the same key name on every session, and set it in the one place in your code that creates sessions, so that no session is missed. Steel stores every value as a string. Do not put secrets in metadata, because Steel shows it in the dashboard. Add metadata has the rules for keys and values, and shows how to change metadata after a session starts.
2. Read each session's cost
Call sessions.cost with the session ID after you release the session. A live session's cost is not final, so the API returns 409 until the session ends. Steel writes the final usage a few seconds after the release, and until then the call returns a cost of zero. So this code reads the cost every 2 seconds until it is final: the call no longer fails with 409, and the cost is more than zero. It stops with an error after 30 seconds. In Go, a deferred release runs only when run returns, so release the session before this call.
async function finalCost(sessionId: string) {
const deadline = Date.now() + 30_000;
for (;;) {
try {
const cost = await client.sessions.cost(sessionId);
if (cost.totalCost > 0) return cost;
} catch (error) {
if (!(error instanceof Steel.ConflictError)) throw error;
}
if (Date.now() > deadline) throw new Error(`The cost of session ${sessionId} is not final after 30 seconds.`);
await new Promise((resolve) => setTimeout(resolve, 2000));
}
}
const cost = await finalCost(session.id);
console.log(JSON.stringify(cost, null, 2));import json
import time
from steel import ConflictError
def final_cost(session_id):
deadline = time.monotonic() + 30
while True:
try:
cost = client.sessions.cost(session_id)
if cost.total_cost > 0:
return cost
except ConflictError:
pass
if time.monotonic() > deadline:
raise RuntimeError(f"The cost of session {session_id} is not final after 30 seconds.")
time.sleep(2)
cost = final_cost(session.id)
print(json.dumps(cost.to_dict(), indent=2))import (
"encoding/json"
"errors"
"net/http"
"time"
)
deadline := time.Now().Add(30 * time.Second)
var cost *steel.SessionCostResponse
for {
result, err := client.Sessions.Cost(ctx, session.ID)
var apierr *steel.Error
if err != nil && (!errors.As(err, &apierr) || apierr.StatusCode != http.StatusConflict) {
return err
}
if err == nil && result.TotalCost > 0 {
cost = result
break
}
if time.Now().After(deadline) {
return errors.New("the session's cost is not final after 30 seconds")
}
time.Sleep(2 * time.Second)
}
out, err := json.MarshalIndent(cost, "", " ")
if err != nil {
return err
}
fmt.Println(string(out))let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
let cost = loop {
match client.sessions().cost(&session.id).await {
Ok(cost) if cost.total_cost > 0.0 => break cost,
Ok(_) => {}
Err(error) if error.status() == Some(409) => {}
Err(error) => return Err(error.into()),
}
if std::time::Instant::now() > deadline {
return Err("the session's cost is not final after 30 seconds".into());
}
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
};
println!("{}", serde_json::to_string_pretty(&cost)?);In Rust, this code needs cargo add serde_json.
{
"id": "de53d365-d381-43a8-a9be-308f2f091533",
"currency": "usd",
"unit": "dollar",
"totalCost": 0.000022,
"usage": {
"browser": {
"value": 1,
"unit": "second"
},
"proxy": {
"bytes": 0
},
"captcha": {
"solves": 0
}
}
}totalCost is the session's cost in US dollars, and usage shows what it comes from: browser time, bytes through Steel proxies and CAPTCHA solves.
The best time to read the cost is when your job ends. Store it in your own database next to the customer and job. Then a report can read your own database instead of calling the API once for each session. Session cost explains the response.
3. Add up cost by customer
To build a report from the API, list a period's sessions, read each one's cost, and add the costs up by the customer_id key. This program does that for November 2026.
import Steel from "steel-sdk";
const client = new Steel();
const micros = new Map<string, number>();
for (const status of ["released", "failed"] as const) {
for await (const session of client.sessions.list({
status,
createdAfter: "2026-11-01T00:00:00Z",
createdBefore: "2026-12-01T00:00:00Z",
})) {
const customer = session.metadata?.customer_id;
if (!customer) continue;
const cost = await client.sessions.cost(session.id);
micros.set(customer, (micros.get(customer) ?? 0) + Math.round(cost.totalCost * 1e6));
}
}
for (const [customer, total] of micros) {
console.log(customer, (total / 1e6).toFixed(6));
}from collections import defaultdict
from steel import Steel
client = Steel()
micros = defaultdict(int)
for status in ("released", "failed"):
for session in client.sessions.list(
status=status,
created_after="2026-11-01T00:00:00Z",
created_before="2026-12-01T00:00:00Z",
):
customer = (session.metadata or {}).get("customer_id")
if not customer:
continue
cost = client.sessions.cost(session.id)
micros[customer] += round(cost.total_cost * 1_000_000)
for customer, total in micros.items():
print(customer, f"{total / 1_000_000:.6f}")package main
import (
"context"
"fmt"
"log"
"math"
"time"
"github.com/steel-dev/sdk/go"
)
func main() {
if err := run(context.Background()); err != nil {
log.Fatal(err)
}
}
func run(ctx context.Context) error {
client := steel.NewClient()
micros := map[string]int64{}
var customers []string
for _, status := range []steel.SessionListParamsStatus{
steel.SessionListParamsStatusReleased,
steel.SessionListParamsStatusFailed,
} {
iter := client.Sessions.ListAutoPaging(ctx, steel.SessionListParams{
Status: steel.F(status),
CreatedAfter: steel.F(time.Date(2026, time.November, 1, 0, 0, 0, 0, time.UTC)),
CreatedBefore: steel.F(time.Date(2026, time.December, 1, 0, 0, 0, 0, time.UTC)),
})
for iter.Next() {
session := iter.Current()
customer := session.Metadata["customer_id"]
if customer == "" {
continue
}
cost, err := client.Sessions.Cost(ctx, session.ID)
if err != nil {
return err
}
if _, ok := micros[customer]; !ok {
customers = append(customers, customer)
}
micros[customer] += int64(math.Round(cost.TotalCost * 1e6))
}
if err := iter.Err(); err != nil {
return err
}
}
for _, customer := range customers {
fmt.Printf("%s %.6f\n", customer, float64(micros[customer])/1e6)
}
return nil
}use futures_util::StreamExt;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = steel_rs::Client::new();
let mut micros: std::collections::HashMap<String, i64> = std::collections::HashMap::new();
let mut customers: Vec<String> = Vec::new();
for status in [
steel_rs::SessionListParamsStatus::Released,
steel_rs::SessionListParamsStatus::Failed,
] {
let sessions = client
.sessions()
.list_auto_paging(steel_rs::SessionListParams {
status: Some(status),
created_after: Some("2026-11-01T00:00:00Z".to_owned()),
created_before: Some("2026-12-01T00:00:00Z".to_owned()),
..Default::default()
});
let mut sessions = std::pin::pin!(sessions);
while let Some(session) = sessions.next().await {
let session = session?;
let customer = session
.metadata
.and_then(|metadata| metadata.get("customer_id").cloned())
.unwrap_or_default();
if customer.is_empty() {
continue;
}
let cost = client.sessions().cost(&session.id).await?;
if !micros.contains_key(&customer) {
customers.push(customer.clone());
}
*micros.entry(customer).or_default() += (cost.total_cost * 1e6).round() as i64;
}
}
for customer in &customers {
println!("{customer} {:.6}", micros[customer] as f64 / 1e6);
}
Ok(())
}In Rust, the program also needs cargo add futures-util. Run the program:
npx tsx cost-report.mtspython cost_report.pygo run .cargo runThe program prints one line for each customer, with the total in US dollars:
cus_1042 0.000088The program adds the costs as whole millionths of a dollar, so that rounding errors do not add up over many sessions. It lists released and failed sessions in two passes, because the list leaves out failed sessions unless you ask for them. It skips live sessions, which have no final cost yet.
To report on one customer, pass metadata: { customer_id: "cus_1042" } to sessions.list, so that the list holds only that customer's sessions. For your organization's usage and bill, see Billing and usage.
Check that it worked
Run the report a few seconds after you release the session from Tag sessions with metadata, so that its cost is final. The report has a line for cus_1042, and its total is at least the totalCost that Read each session's cost printed for that session. If the total is 0.000000, the report ran before Steel wrote the final usage, so run it again.