I Built a Claude Code Usage Tracker with TimescaleDB
Read full transcript 23 segments
-
I thought it would be a good idea to track what my cloud code usage would look like at API pricing. I currently pay a monthly subscription on the 20x Max plan and this comes out to about $200 a month, but I get a lot more in API usage limits. However, these generous usage limits may change in the future, so I want to know what my actual usage is at API pricing. The fun part is that this is also an interesting engineering problem. We have to track cloud requests in real time, store them in some database, and then have an efficient way to query this data. So, of course, I built a .NET application using PostgreSQL with the TimeScale DB extension, and I want to walk you through the architecture and the design decisions in this video. And this is why I built TokenScope. It runs using a React client application and a .NET backend that connects with cloud code. I have a couple of views for different data sources, and this is my actual cloud code usage. Of course, the dollar amount is an estimate based on the API pricing as of October 2026. So, when I say you have a couple of sources, the default one is cloud history, and this just picks up the sessions that I have stored locally and then imports them into my application. Now, you can see this isn't perfect because I've got a bunch of days with zeros, but to be honest, I wasn't using cloud as much this month as I was in previous months as I was mainly using Codex as my daily
-
driver. Nonetheless, I did have some usage spikes and then more consistent usage in the last seven days, and the UI lets you drill down into the level of granularity that you want to see, and it displays the respective data within that time frame. The other data source, which is a very interesting one, is live telemetry. And how this works is it hooks into the cloud code open telemetry stream. And I'm going to explain how all of this works together as we go through the video. Now, the core questions that I want my application to answer is what does my cloud code usage look like? Let me to the history tab just so we have more data to work with. So I want to answer how much I'm using CloudCode, which models am I using and how much. For example, now I can see that Fable and Opus cost about the same in API pricing. With Fable, I have around 3,300 usage records and with Cloud Opus 55 I have more than 11,000. So I can conclude just from this that Opus 55 is more cost effective. And then the estimate on my cost breakdown is a good reference point for what I might expect if I no longer have access to my subscription or it becomes less subsidized. So how my system works is it hooks into CloudCode events that it emits for the API requests that it produces and I store all of these based on a timestamp inside of my database. And this is a perfect use case for a time series database. Now you could look for some specialized system that solves this, but I didn't
-
have to look far as Postgres has an awesome extension that you can install called Timescale, which turns Postgres into a fully fledged time series database. I'll talk more about the hosting options for using Timescale and for my usage I decided to go with a managed version of Timescale which runs in Tiger Cloud. This is what the high level architecture of the entire system looks like and everything starts with CloudCode and its open telemetry stream. Of course, there is detailed documentation about open telemetry with CloudCode and I'm going to leave the link to this in the description of this video if you want to learn more. How we are going to use this is we're going to expose an open telemetry endpoint on our .NET API to ingest open telemetry logs. Then I'm going to store these logs so that we can buffer the incoming logs as we process them and I'm going to have a background writer pick up the data from this queue and then store it inside of my database. The React client is going to tie everything together and allow us to query the data inside of our Timescale database. The token scope application filters out and only stores API requests out of the open telemetry logs. And here's the API request in my code. And the key piece of information that I'm going to collect is the timestamp for this API request. Then I'm going to record the source which can either come from the history or it could be live telemetry data that we are ingesting inside of the current session.
-
Going to record the developer, the session ID, the model. And then the interesting parts are the number of input and output tokens, cache tokens, and of course the cost of this request. Now note that this doesn't represent a single prompt that you send to your agent. One prompt can create multiple API request calls. So the best you can do to extrapolate this is to group it by the session ID. And this is what most of my queries do. They group a large number of API requests by a certain dimension. This dimension can be either a developer, a session ID, a model, or the timestamp which I showed you at the start in the token scope UI where we are interested in some sort of granular view of our usage over an hourly, daily, weekly, or monthly basis. So we have timestamped and then data being streamed into our application. And most of our queries are going to be aggregations over this data that we want to do efficiently. So that's why this is a good problem to solve with a time series database. So we have API requests that we can identify with a single request ID. However, this doesn't match the type of query that I want to run. I'm more interested in some sort of aggregation, let's say over a time period, for example, the last 30 days. And this could represent a lot more than a single request. So I want to calculate these group totals in a fast and efficient way. And vanilla Postgres can handle this just fine. But you have to be aware that you're going to run the
-
calculations every time you run the queries. Of course, you could mitigate this with a materialized view, but then you run into the problem of serving stale data to your client application. Depending on how often you interact with Cloud Code, the telemetry can either be sparse, for example, every 10 or 20 minutes, or it can be very dense. But nonetheless, this is time series data, as we can tie a timestamp to each request and nicely group it into some sort of range, let's say between 9 and 10 a.m. Then we want to aggregate all of the requests in this time range and calculate some values. For example, how many tokens did I spend from 9 to 10 a.m. this morning? And I can use this information to extrapolate my tokens per hour usage if that was an interesting metric. And this is why I decided to use TimescaleDB for this problem because it has some interesting data structures that allow me to easily build the aggregations that I want to serve on my user interface. Now a little bit about TimescaleDB because if you decide to research it, you may run into some confusion, so I want to help you out. So the company that created and is still developing and maintaining TimescaleDB is called Tiger Data. They are also the sponsor of today's video. Now when it comes to how you could run your Timescale database with the Token Scope application, you got two options. You can self-host this just fine inside of a Docker container, but you take up all the operational workload. This means maintenance, database backups, updates, monitoring, and recovery. But if you're
-
looking for a managed solution, which is what I'm going to use in this video, you can check out Tiger Cloud. Tiger Data operates Tiger Cloud and they have an amazing offer if you want to get started with Timescale, where if you sign up with the link that's going to be right under this video, you're going to get $1,000 of cloud credits to spend for your Timescale database. So regardless of which way you decide to go, self-hosted or Tiger Cloud, remember that this is still Postgres under the hood. So everything that you're already used to using, like mPgSQL or Dapper, is going to work just fine with Timescale. Or building block in TimescaleDB is called a hypertable. Now from the outside, it looks just like a regular Postgres table. You send a typical insert statement and write your data into the database. Our hyper table is going to be called API requests. You can query this data just fine with select statements, so nothing really changes. But what happens under the hood is Timescale is going to partition your data into chunks that is going to store separately. Inside of token scope, I decided to use daily chunks, so all of the requests for one day belong to one chunk. And this comes with some very interesting benefits. For example, when we send a query to find specific rows that belong to, let's say, the day two chunk, Timescale knows which rows belong to this partition and it can efficiently filter out any rows that wouldn't satisfy the query. This means that instead of filtering the entire table to find the relevant rows, Timescale can
-
serve you just the specific rows that you're interested in, and this drastically improves the performance of analytics queries. However, these are still just rows in the database, so you will still have to aggregate this data if you want to get information like usage per model or usage for a given session. And this is where another feature of Timescale comes in called continuous aggregates. So how this works is we've got our incoming requests that we partition based on the timestamps and store them inside of chunks, and then we can take these same rows and aggregate them based on the timestamp. Let's say group them by the hour and by the model and perform the required aggregations. For example, we can do a count to know how many records we have. We can sum the API costs. We can sum the number of tokens, and we store these inside of a specialized materialized view called a continuous aggregate. Now this is different from your standard materialized view in Postgres, and this is also different from your typical view in SQL. So let me just explain the differences. So a view is basically a shorthand for some complex query that you want to run. Instead of sending the full SQL statement to the database every time, you do a select on the view, and it's just a shorthand for a complex query. This also means that the query is executed every time you call the view. A materialized view stores the results of this query so that repeated queries don't have to re-execute it. But this also means that the data becomes stale after you've run it for the first time.
-
So you have to manually refresh the materialized view to continue gaining the performance benefits. With Timescale continuous aggregates, you define your aggregates once using a simple SQL statement, then you configure a so-called policy that defines how often the continuous aggregate is refreshed. And this comes in handy because nobody guarantees that your API requests are going to be streamed to your application in order. And for example, if you import one week old history, you would want to update one week old aggregations. And Timescale takes care of all of this for you automatically. Here's the SQL for defining our hypertable, and it's just a create table statement with the table name. You define your columns just the same as before. Now what's different is a couple of statements here that are specific to TimescaleDB. So this is what turns our table into a hypertable. We also define the partition column here, and we want to partition by the time column. We configure what is the time interval for our chunks, and in case of token scope, I want to use one day chunks. Segments allow Timescale to group our data based on certain columns, in this case the source and the developer, and this allows it to optimize the storage of the data. Order by tells it to sort based on a given column, in this case by the timestamp in descending order. And then the sparse index allows us to define a bloom filter, in this case by the session ID, and this allows the database to skip
-
entire days worth of data when searching for a specific session as it can efficiently figure out if the session that we are looking for is inside of a given chunk or not. So this covers the building blocks of working with TimescaleDB. Now the next thing I need is an actual database instance, which I'm going to create in Tiger Cloud. The token scope backend and the React client are going to run locally on my machine inside of a Docker container. And of course, I'll be running CloudCode locally as my agent. But my data is going to be stored inside of a PostgreSQL database with the TimescaleDB extension installed, and I'm going to use a managed database operated by Tiger Cloud. Now, the good thing is they offer a very nice CLI that's going to allow me to create my database without ever having to touch a user interface. The one thing we will have to do first is create an account. I'll go over to tigerdata.com and find the Tiger Cloud product, and then you can either click log in or start a free trial, which is what I'm going to do. It's going to take me to this screen where I'll sign up for Tiger Cloud. And as I've already mentioned, if you create an account now, you're going to get $1,000 in credits valid for 30 days that you can use for running your TimescaleDB instance. I'm going to log into my existing account, and I already have a service here that I'm using for my token scope instance, but I wanted to show you a simple way how you can get started. So if you click here, you'll be taken to the Tiger CLI page. Then you can choose your operating
-
system. I'm going to take the command for Windows, and I want to jump into my terminal and install this. So I'm going to drop in the command. Now, this is going to be a no-op basically because I already have it installed, and once this completes, you can run Tiger version just to confirm what the latest version that you have installed is. Then your next step is going to be to authenticate with Tiger Cloud. For this, you're going to run Tiger off log in, and this is just going to take you to the UI where you're going to authorize the CLI to give it access to your Tiger Data org. Going to approve this, and then we can jump back to the terminal, and we have an authenticated session. So now I can say something like Tiger service list, and this will give me any databases I already have inside of Tiger Cloud. If you want to create an instance using the CLI, you can call this command, Tiger service create, pass a name for your new instance. I'm going to call it token scope demo just so that it's different from my existing service. Then I'm going to enable the time series add-on, essentially running TimescaleDB. And when I run this, you're going to see the CLI is going to take a couple of moments as it provisions our instance. Once it's done, we'll be able to use our Timescale instance to store our time series data.
-
So after a couple of moments, our instance is provisioned. We can see some details about it. It's currently in the US East 1 region. And there's also a handy connection string here that you can pass along to your application. I'm going to show you where that is inside of the Timescale source code. But I want to just quickly jump back into TigerGraph Cloud and just refresh the screen here to show you that our new instance shows up and we can go into it and look at some additional details. Now, how do we connect this with our application? Well, I keep coming back to this, but remember that this is just Postgres. So all we need is a connection string. And in this case, I've got two options. You can either call it Timescale or database. Both work just fine. And once you have the connection string defined through an environment variable or app settings, then you're going to add an PG SQL data source and you can start querying your database using PG SQL. I'm just adding Dapper on top to make my queries more manageable.
-
When it comes to our schema, you can just execute the schema SQL here. It contains the applications as well as the hypertable, but I 'm going to go into these a bit later in this video. The application itself is going to ensure that the schema is created when the application starts up. So regardless of if you are self-hosting with a Docker container or running in TigerGraph Cloud, you can just start the application and it's going to provision the database schema. If I go into my actual Timescale instance in TigerGraph Cloud, I can go into the Explorer tab and show you the tables I have inside of the public schema. Now, there are a couple of them that are not relevant for our demo, but here is the API requests hypertable. It has approximately a million rows and 93 chunks. And if you recall, the chunk is one day. So you can see the details about the chunks here, the average chunk size. We also have a couple of aggregations which includes our hourly, daily, or monthly spend. And for each of these you can see their size, how many rows are inside of a specific aggregation, when it was last refreshed, how many chunks there are in total. And you can also see details about the aggregation schema, the definition in SQL that actually creates it, any indexes that exists, details about the chunks, and of course the policy that configures how often the aggregate is recalculated. So now we have our Timescale instance, we can take our API requests that are streamed from
-
Cloud Code. And I want to note that we're only ingesting the data that we actually need. This includes the timestamp, which model we used, the number of tokens, and the cost estimate or the actual cost if it's reported by Cloud. We don't record the prompt or the entire conversation as that's not really relevant. We only care about usage data. Our data is stored in one big table called a hypertable, which is partitioned based on a timestamp into individual chunks, and these chunks represent one day of usage. And this allows us to efficiently run time-based queries. So if we want to get some information about days two and three, Timescale can efficiently find these chunks while filtering out all the ones that aren't relevant for our query. When it comes to storing the data inside of our hypertable, we can use a regular insert, but a more efficient way to do this, especially with large batches of data like in our case, is using a binary copy. And let me show you what this looks like in the code. The core abstraction is the usage event writer.
-
It accepts an MPG SQL datasource that it uses to open up a connection. And essentially what's happening here is we take a batch of API request rows. I'm using a temporary table called request keys to insert these rows first based on the source and the event key. And this is just to filter out any duplicates as we may get retries when ingesting the data, so we don't want to process the same API requests twice as this would make our aggregations show incorrect values. The actual insert is here, which is just a bulk insert using binary copy. The syntax is straightforward. You say copy, specify the table, and then the columns that you want to insert. And in our case, this is going to be a binary insert from standard input. What this looks like in the code is we say begin binary import async. We get back a writer, and we use it to write each row. So we start a row, write the columns that we want into it, and when we are done, we say complete async, and we iterate until we've written all the rows that we need to do. And finally, we commit our database transaction, and everything gets persisted inside of our Hypertable. To show you what a query looks like, let me go into my endpoint for fetching a time series. And this is a generic endpoint that allows me to query my data based on the specific range that I choose. And this can be an hour, a day, seven days, or any other range I choose. And as you can see, this is just a regular SQL query. Now the interesting part is here in this common
-
table expression, where I want to show you that this is just a regular select statement, and I'm selecting from either an aggregation, which I'm going to talk about more in a moment, but essentially they aggregate my usage based on a given period. So this can be either by the minute, by the hour, or by the day. But depending on the range I choose, it may also fall out of what what a specific aggregation takes care of. So I can also query from the API requests Hypertable directly, do my filtering there, and then join all of the data. Back inside of my API endpoint, I just run a select statement on my data and project everything the user interface needs to display. So that's how we actually store and query all of this data. Now the one thing that's missing is how we actually ingest the open telemetry coming from Cloud Code. And I want to show you how this works in real time. So, I've got this Claude Telemetry JSON document, and it basically enables our Open Telemetry stream, and it points it at our local ingest endpoint for Open Telemetry logs.
-
Now, of course, you can set these values globally, and then they're going to apply for every session. But if you want to only use this for one session, I'm going to show you how. But let me just open the UI, and I'm going to switch to the live telemetry view and filter by the last hour of data. And then I'm going to open up the UI and the terminal side by side. And in the terminal, I'm going to say Claude and pass it my Claude Telemetry JSON settings. So, if I run this, it's going to start up a new session that's going to have Open Telemetry configured to stream to my Token Scope application. And then I can send a prompt. For example, explain in two sentences why batching database inserts can improve throughput, do not use tools or modify files. So, just a dummy prompt that's going to produce some usage, and we're going to see it show up inside of our UI in a couple of moments. Don't expect it to be instant as the streaming is an asynchronous process, and depending of how many sessions or agents you've got running, you may see more or less lag in the UI.
-
But eventually, it should converge to the latest data. And this is now served from our Timescale instance inside of Tiger Cloud. So, back to the UI on the full screen, and you can see that we can switch between multiple views of the data. We can see the hourly breakdown. We can also take a look at our usage over the last 24 hours, and none of this is actually handled by the Hypertable by default. Instead, this is where aggregates come in. How they work is we group the data into buckets, and let's say the size of a bucket is 1 hour. So, let's say we have a bucket for 10:00 a.m. and 11:00 a.m., and these two records fall into the 10:00 a.m. bucket, but the record with a timestamp of 11:00 a.m. falls into the next bucket. The bucket itself is just a grouping of data. What then do is we take this grouping and we run aggregations on it. We can count how many API requests there are in a given time period or sum the token spend or costs and we store all that inside of a materialized view.
-
Inside of token scope, I have three aggregations. The spend for every one minute, the spend for every one hour, and then the daily spend which is calculated using the hourly spend. All of these are going to have a dedicated refresh policy which determines how often the aggregate or the materialized view gets updated. And what's important to note here is the time scale also takes care of for example, if you insert some new data into a fairly old bucket, it's still going to be able to detect that and recalculate the aggregate and update the materialized view. To show you what that looks like inside of our schema, here's the query to define an aggregate and this one is the spend for a minute. So this is mostly used in our live data that you just saw and you created as a materialized view. However, we make this a continuous aggregate. Setting materialized only to false allows us to see updated data without having to wait for the next interval to refresh the aggregate. Then we define the query that makes up our materialized view. So this is just another select statement. We select from our hyper table, API requests, and we group by the bucket which is a time bucket with an interval of one minute based on our timestamp column. We also group by the source which can be our cloud history or live telemetry data. We group by the developer and we group by the model, let's say Opus or Fable. And then we run
-
our aggregations that we want to store inside of our aggregate. So we count the number of requests, we sum the costs and the number of input and output tokens so that this data is readily available to display in the user interface. Similarly, there is the aggregate for the one hour spend and also the aggregate for the daily spend where the difference is that we select from the hourly aggregate and then we group by the same data. Once we have these in place, we can run a function called add continuous aggregate policy and this determines how often we update the aggregates. So we specify the aggregate name and then the important part is this schedule interval here which says that we're going to update our aggregate every one minute for the one minute roll up then every five minutes for the hourly spend then every hour for the daily spend. And we can actually measure how much of an improvement this gives us compared to regular SQL queries. So I've got an endpoint here that can run a benchmark comparing two queries that return the same data. One of them selects from the API request table and calculates the data we need and the other one selects from our daily spend and then the rest of this is just comparing the results of the two queries to make sure that the data they return is identical. If I go back to token scope and I switch the data source to my demo team which just contains some synthetic records so that we have more
-
data to work with, this is where I can run a comparison to compare my two queries using either the raw API request table or the daily spend aggregate. And we want to calculate the spend for the last 90 days by a given model. So if I run this, it's going to execute the queries against my real database running in Tiger Cloud and we're going to see the results that show us that our aggregate is nearly five times faster. And this is something you might expect, right? Because this is a materialized view. So it's going to be doing less work at query time and this is why we decided to use a time series database. So with just 1 million records or slightly less, our query takes almost 800 milliseconds whereas with an aggregate it's 160 milliseconds. You can see it's a lot more efficient. So I think you can easily extrapolate from here which one of the easiest is going to scale if we were using Token Scope inside of a real team with a lot more usage. Now another cool thing I've built into Token Scope is an MCP server. I'm going to make a whole dedicated video about building MCP servers, but essentially there's a nice library that you can use to solve most of the pain points and you just say add MCP server to register your services, you configure your available tools on the MCP server and then you expose it by mapping an MCP endpoint that agents can connect to. Now if we take a look at our tools, we're going to allow our agent to ask some
-
questions about our usage and we can run SQL queries behind the scenes to return the required data. So to show you how this works, I'm going to open up my terminal and I'm going to say Claude MCP add pointed to the Token Scope MCP running on this endpoint. This is going to configure the MCP server and now I'm going to open up a new session with Claude and I'm going to type / MCP and this is going to list out the MCPs that I have and you can see that Token Scope is there and we can use it. So I'm going to drop in this prompt and I'll say use Token Scope's get spend breakdown tool and group by agent for the last 30 days and I want you to show me the three highest spend agents and their estimated API costs. So I just want to show you here that when we run this, it's going to actually use our MCP server so you can see calling Token Scope here and if you expand this, it's going to show you the specific tools that Claude decided to use to answer our specific query and here's the breakdown. If I go here, you can see we called the get spend breakdown tool and if I visit the UI, pick live telemetry and the last hour, we can see the individual tool call here. You can see this cost us 25 cents in API pricing and another thing you can do is use the Tiger Cloud MCP server.
-
You can check if this is installed using Claude MCP get and then the name of the MCP server is Tiger. You can install it by running Tiger MCP install and then specify CloudCode as your agent. And then if I open up a new CloudCode session, I'm going to drop in this prompt where I want to tell it to use the Tiger MCP to inspect my service running inside of Tiger Cloud. And this can be useful if you want to get some information about your database. And this also has a lot of additional tools. You can literally use it to manage your Timescale instance. It can create an instance, delete it, run queries to fetch data that you want to know about or update your schema. And you do all of this using the integration with CloudCode. So earlier I showed you the manual way using the CLI, but of course you can also use the MCP if you prefer using agents. And then here's the response from CloudCode and it lists out what we have in our database, the aggregations that we have and the source of these aggregations. You can see the level of detail that we get from the Tiger MCP. Token Scope is going to be open source and available on my GitHub.
-
So you can download it and start using it today. I'm going to leave the link to it in the description of this video and you can run it either with a self-hosted TimescaleDB instance or a managed one with Tiger Cloud. If you sign up for Tiger Cloud today using the link that's going to be in the pinned comment under this video, you're also going to get $1,000 in credits that you can use for running your Timescale database. What started as a fun experiment to see if I could track my CloudCode usage turned into a very useful example of when a time series database makes sense. By making Token Scope completely open source and free, you'll be able to find it on my GitHub account and there's simple instructions there that you can give to CloudCode and it's going to run it locally for you and you can start tracking your own usage. If you enjoy this video, consider smashing the like button to let me know. Thanks a lot for watching and until next time, stay awesome.
Summary
This video discusses the development of TokenScope, a custom monitoring application designed to track and analyze cloud code usage at API pricing. The architecture features a React frontend, a .NET backend that ingests OpenTelemetry streams, and a PostgreSQL database utilizing the Timescale DB extension for efficient time-series data management. The practical takeaway is that tracking real-time telemetry and aggregating usage data enables developers to accurately estimate costs and evaluate model cost-effectiveness in anticipation of potential subscription changes.