Session cost
After a session ends, Steel computes its cost in US dollars, along with the usage behind the cost. Use the cost to bill your own customers for their sessions, or to find the jobs that cost the most. On Launch and Scale, the cost counts browser time by the second, as your invoice does. Pricing has the rates.
Before you begin
Put your Steel API key in the STEEL_API_KEY environment variable, and install the Steel SDK for your language: TypeScript, Python, Go or Rust.
Get a session's cost
Call sessions.cost with the session ID, after you release the session. While the session is live, the call fails with 409:
Session cost is available after the session has been released. Release this session first, then retry once final usage has been written.For a few seconds after the release, until Steel writes the final usage, the call returns a totalCost of 0. This program creates a session and releases it. Then it reads the cost every 2 seconds until the cost is final: the call no longer fails with 409, and totalCost is more than 0. It stops with an error after 30 seconds, and it prints the cost and usage.
import Steel from "steel-sdk";
const client = new Steel();
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 session = await client.sessions.create();
try {
console.log(`Created session ${session.id}`);
} finally {
await client.sessions.release(session.id);
}
const cost = await finalCost(session.id);
console.log("Total cost:", cost.totalCost.toFixed(6));
console.log(JSON.stringify(cost.usage, null, 2));import time
from steel import ConflictError, Steel
client = Steel()
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)
session = client.sessions.create()
try:
print(f"Created session {session.id}")
finally:
client.sessions.release(session.id)
cost = final_cost(session.id)
print(f"Total cost: {cost.total_cost:.6f}")
print(cost.usage.to_json())package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"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()
session, err := client.Sessions.New(ctx, steel.SessionNewParams{})
if err != nil {
return err
}
fmt.Printf("Created session %s\n", session.ID)
if _, err := client.Sessions.Release(ctx, session.ID); err != nil {
return err
}
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)
}
fmt.Printf("Total cost: %.6f\n", cost.TotalCost)
out, err := json.MarshalIndent(cost.Usage, "", " ")
if err != nil {
return err
}
fmt.Println(string(out))
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::default())
.await?;
let result: Result<(), Box<dyn std::error::Error>> = async {
println!("Created session {}", session.id);
Ok(())
}
.await;
client.sessions().release(&session.id).await?;
result?;
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!("Total cost: {:.6}", cost.total_cost);
println!("{}", serde_json::to_string_pretty(&cost.usage)?);
Ok(())
}In Rust, the program also needs cargo add serde_json. Run the program:
npx tsx cost.mtspython cost.pygo run .cargo runThe session ran for less than a second, which counts as one second, with no proxy and no CAPTCHA:
Created session ddec3ee7-769e-4b1d-b69b-f19d03d55e44
Total cost: 0.000022
{
"browser": {
"value": 1,
"unit": "second"
},
"proxy": {
"bytes": 0
},
"captcha": {
"solves": 0
}
}Created session 70332bf7-00ca-4a72-9f6c-e72b5f50ad96
Total cost: 0.000022
{
"browser": {
"unit": "second",
"value": 1.0
},
"captcha": {
"solves": 0
},
"proxy": {
"bytes": 0
}
}Created session 8979b345-d001-4e8f-8e34-df26dbae6275
Total cost: 0.000022
{
"browser": {
"unit": "second",
"value": 1
},
"captcha": {
"solves": 0
},
"proxy": {
"bytes": 0
}
}Created session 5e263cd2-662d-42a3-b24e-5490afad5f0a
Total cost: 0.000022
{
"browser": {
"unit": "second",
"value": 1.0
},
"captcha": {
"solves": 0
},
"proxy": {
"bytes": 0
}
}The response has these fields:
| Field | What it holds |
|---|---|
totalCost | The session's cost in US dollars, exact to the millionth of a dollar. Steel does not round it to whole cents. |
currency, unit | Always usd and dollar. |
usage. | The browser time, in value and unit. On Launch and Scale, the unit is second, and Steel rounds each session's time up to a whole second, as your invoice does. Some older plans use minute. Steel counts no more time than the session's timeout. |
usage. | The bytes that the session sent and received through a Steel proxy. Steel does not count the bytes through your own proxy. |
usage. | The CAPTCHAs that Steel solved in the session. |
Steel computes totalCost from the usage in the response: the browser time, proxy bytes and CAPTCHA solves, each at your plan's rate.
To lower a session's cost:
- Release the session as soon as the work is done, and set
inactivityTimeout. See Set timeouts. - Block what the task does not need, so that less data goes through the proxy. See Reduce bandwidth.
- Use a Steel proxy and CAPTCHA solving only in the sessions that need them.
Add up costs across sessions
To add up the cost of one customer or job, tag its sessions with metadata, list them with a metadata filter, and add up their totalCost values. Track cost per customer shows the whole task.
For your whole organization's usage and bill, see Billing and usage.
Check that it worked
Check totalCost against the usage. Multiply each usage value by your plan's rate in Pricing, and add the results. The sum, to the millionth of a dollar, is totalCost. For the program's session, 1 second at Scale's $0.08 per hour gives the 0.000022 that the program prints.