How to safely add paid AI features to a desktop app

By

Tagged: AI

Protect your AI API keys and margins with server-side authentication, per-user budgets, rate limits, and a global spending cap.

Suppose you sell a desktop app for $49. A customer pays once, downloads it, and starts using it, and every time they click Generate, the app calls an AI model on your dime. That changes the math of desktop software, because a one-time purchase doesn’t cap what that customer can cost you over the next months or years. You need an architecture that puts a hard ceiling on your bill before you ship.

Why a lifetime license can become a liability

Traditional desktop apps have a great property: once someone downloads the binary, almost all the work runs on their machine. Adding a hosted AI feature changes that, because every request burns a paid resource on your account.

Say one generation costs you $0.04, and an active customer runs 10 generations across 5 projects every week. Here’s what that adds up to:

10 generations × 5 projects = 50 generations/week
50 × 4.33 = 217 generations/month
217 × $0.04 = $8.68/month

At that pace, a $49 lifetime license covers less than six months of inference, and that’s before payment fees, hosting, support, taxes, or any profit. You can see how that plays out over a full year below, where the rising line is your inference bill and the flat line is the $49 they paid:

One customer: inference cost vs license price ($)020406080100123456789101112Month

The two lines cross between month five and month six, and after a year that single customer has cost you $104. Whenever you price an app with hosted AI, work from this basic equation:

purchase price - lifetime AI cost = gross profit

When you attach the word lifetime to uncapped AI usage, you’re signing up for an uncapped bill.

Never put your model API key in the application

The easiest architecture to build is also the worst one to ship, where the desktop app talks straight to the model provider:

Desktop app → AI provider

In this setup, your Anthropic, OpenAI, or Google API key lives inside the app bundle. That breaks down in two ways right away.

First, you can’t enforce a trustworthy usage limit on a computer you don’t control. Your customer owns that machine, so they can modify the app, replay requests, or bypass your interface completely. Second, anyone motivated enough can extract the API key from the binary. Obfuscation makes that harder, sure, but any secret you ship to a customer’s machine should be treated as public. Once your key leaks, someone doesn’t even need your app anymore. They can call the provider directly while you pay the bill.

Put your server in the middle

To stay in control, the model provider should only accept requests from infrastructure you own. Put a backend between the app and the provider like this:

Desktop app
    ↓
Your backend
    ↓
AI Gateway
    ↓
AI provider

Now the desktop app sends a license or session token to your backend. Your server validates the token, looks up the customer account, and only then forwards the request to the model.

Putting your server in the middle gives you one place to decide:

  • whether the license is valid
  • which customer is making the request
  • which model they’re allowed to use
  • how fast they can send requests
  • how much they can spend
  • whether the request should continue at all

Your model API key stays in a server-side secret and never reaches the customer’s machine.

If you want to build this layer on Cloudflare, a Worker is a great fit. My complete Cloudflare guide covers Workers, AI Gateway, limits, and production operations, and I also have a dedicated Cloudflare AI Gateway guide covering setup, authentication, logging, caching, and model calls.

Fig 1 · 1/4Check identity, speed, and spending
Authenticate the license

Do not trust a user ID from the client

Watch out for a common mistake once you put a backend in place. Your desktop app might send a payload like this:

{
  "userId": "customer_123",
  "prompt": "Summarize this project"
}

Never use that userId for billing or limits. Any customer can swap it to customer_456 and charge their usage to someone else’s account.

Instead, authenticate the request on the server first and derive the identity from the token:

Desktop app sends license token
    ↓
Backend validates the token
    ↓
Backend finds customer_123
    ↓
Backend attaches trusted customer metadata
    ↓
AI Gateway receives the request

Even if the client sends a userId in the body, your backend ignores it and trusts only what comes back from token verification. Without this step, per-customer limits won’t hold up, because anyone could bill their tokens to another user.

Add the trusted customer ID to each model request

Once your backend knows who’s making the request, attach that identity to the AI Gateway call. Cloudflare AI Gateway accepts custom metadata through the cf-aig-metadata header, like in this Worker example:

const customer = await authenticateLicense(request, env)

const response = await fetch(env.AI_GATEWAY_URL, {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${env.AI_GATEWAY_TOKEN}`,
    'Content-Type': 'application/json',
    'cf-aig-collect-log-payload': 'false',
    'cf-aig-metadata': JSON.stringify({
      user_id: customer.id,
      product: 'project-writer',
    }),
  },
  body: JSON.stringify({
    model: 'openai/gpt-5.5',
    messages: [
      {
        role: 'user',
        content: 'Summarize the current project',
      },
    ],
  }),
})

Here, authenticateLicense() represents your own authentication or licensing check, and it has to reject invalid, expired, and revoked tokens. AI_GATEWAY_URL holds your server-side gateway endpoint, whose credentials never leave the server. The key detail is where customer.id comes from: your backend looks it up after authenticating the token rather than letting the desktop app choose it.

Keep email addresses, prompts, license keys, and other secrets out of cf-aig-metadata, since metadata shows up in your gateway logs.

If you use Cloudflare Access, there’s another option. When a request reaches an Access-protected AI Gateway custom domain with a valid user identity, Cloudflare adds a trusted cf.user_id automatically, so you don’t need to pass your own identifier. For a consumer desktop app, though, keeping auth in your own backend is usually easier, because it gives you direct control over licenses, plans, refunds, and credit purchases.

Use three separate limits

A single limit won’t protect you from every failure mode, so stack three different ones together.

Limit how quickly customers can send requests

Start with a rate limit to control request speed. A typical rule looks like this:

20 requests per customer per hour

This catches retry loops, automation, and obvious abuse before they hammer the rest of your backend. Apply it to the authenticated customer ID rather than just the IP address, because multiple customers can share an IP and one customer can switch networks. An IP limit is still useful as a secondary abuse signal, just don’t rely on it as your customer identity.

Limit how much each customer can spend

Next, add a spending limit to cap how much money any single customer can use:

$5 per customer per month

Cloudflare AI Gateway spend limits let you split a rule by custom metadata such as user_id, giving every customer an independent budget.

Once someone hits their cap, the gateway returns a 429 response until the budget window resets. Catch that status in your app and show a clear message instead of a generic network error:

You used this month's included AI allowance.
It resets on October 1, or you can add more credits now.

The connection is working fine here, so tell the customer plainly that they’ve reached their allowance and when it resets.

Limit the entire product

Finally, add a global spending limit across the whole app as a circuit breaker for your own bugs:

$500 across the entire application per month

Sooner or later, a bad release can skip an auth check, drop the customer metadata header, or kick off a request loop across active installs. A global cap makes sure a product bug turns into a temporary pause instead of an unlimited bill.

Rate limits and spending limits solve different problems

Rate limits and spending limits answer two different questions. A rate limit tells you:

How quickly can this customer use the feature?

A spending limit tells you:

What is the maximum this customer can cost me?

You need both, because ten small requests and ten large requests can cost wildly different amounts. Someone can stay well under a request-count limit while sending huge prompts and asking for long responses. Counting tokens gets closer to real cost than counting requests, and tracking dollars directly is better than both.

On top of gateway limits, restrict input size and max output tokens right in your application layer. If a feature only needs a 500-word summary, don’t accept a 2-million-token project or allow a 30,000-token response.

Know what a hard limit cannot guarantee

Cloudflare AI Gateway spend limits block new requests when the tracked budget is exceeded, though you should know how that tracking behaves. Cost is an estimate based on token counts and known model prices, and the limits are eventually consistent because each request’s cost is recorded after it finishes. Several concurrent requests can briefly push an account slightly past its budget.

Treat $5 per month as a strong control rather than a mathematically exact ceiling, and leave margin in your unit economics. If paying $5.20 instead of $5 breaks the product, your pricing doesn’t have enough room.

Use your model provider’s billing controls as an extra boundary whenever they offer hard enforcement. Check the wording carefully in their dashboard, though: some providers call a notification threshold a “budget” even though it only emails you after you cross it, and an alert won’t stop the spending.

Decide what happens after the allowance is used

Once you know how to cap spend, decide what happens when a customer uses up their included AI budget. You have four solid pricing models to pick from.

Include a fixed number of generations

The easiest model to explain on a sales page is a fixed count of generations:

$49 includes 500 AI generations

Customers grasp this right away, though generations don’t all cost the same amount of tokens. You’ll still need token caps and spending limits running behind the scenes so oversized prompts don’t throw off your math.

Include a dollar-based allowance

You can also bundle a fixed inference budget in dollars with the license:

$49 includes $5 of managed AI usage

This maps directly to your provider bill. Since credits or generations are often easier for customers to understand than tiny dollar amounts, you can show friendly credits in the interface while tracking dollars internally.

Charge a subscription

If people use the AI feature regularly, a subscription lines up your recurring revenue with your recurring model costs:

$19/month including up to $5 of AI usage

Your maximum inference cost resets each time the customer’s payment goes through, which makes your margin much easier to model.

Let customers bring their own key

With bring your own key (BYOK), the customer enters their own provider API key:

Customer → their AI account → their bill

You’re selling the desktop app and its workflow, and the customer pays their provider directly for inference. That works well for power users, though it adds setup friction for everyone else and gives you less control over model availability.

My favorite setup is a hybrid model:

  • regular customers get a small managed allowance out of the box
  • power users can plug in their own provider key when they want more

New customers get a feature that works immediately with no setup, and heavy users don’t create an unlimited bill for you.

Calculate the allowance before setting the price

Before you pick a price or an allowance, start by measuring one complete operation. A single generation often triggers more than one model call behind the scenes, like classifying input, retrieving context, generating a result, and validating it. Add up the cost of the whole workflow:

input tokens
+ cached input tokens
+ output tokens
+ tool calls
+ retries
= cost per operation

Then estimate normal monthly usage for a typical customer:

cost per operation × operations per month
= expected AI cost per customer

Run the exact same calculation for a heavy customer, because averages won’t protect you from the expensive end of your user base. Let that calculation set your allowance instead of picking $5 because it looks reasonable.

The architecture I would use

For a paid desktop app with hosted AI, start with a stack like this:

Desktop application
    ↓
Product authentication and license validation
    ↓
Server-side API
    ↓
Per-customer rate limit
    ↓
AI Gateway with per-customer spend limit
    ↓
AI provider

Alongside that core flow, build in these safeguards from day one:

  • a global gateway spending limit
  • strict input and output token limits
  • separate development and production gateways
  • logs without stored prompt and response bodies when content is sensitive
  • a clear allowance screen inside the app
  • a BYOK option for heavy users

With this setup, the desktop app contains no unrestricted model credentials.

You can skip all of this for a local feature running a model entirely on the customer’s computer, since there’s no paid inference account to protect. And for hosted AI with an unpredictable workload, avoid lifetime unlimited plans. A subscription, prepaid credits, or BYOK is much safer for the business.

Put a number on your worst case

Treat AI usage like any other paid cloud resource. You wouldn’t give every customer unlimited access to your AWS account, so don’t give them unlimited access to your AI budget either.

Before you ship, make sure you have concrete numbers for these three questions:

What can one customer cost me this month?
What can all customers cost me this month?
What happens when either limit is reached?

If any of those answers is still “unlimited,” put a cap in place before you release the feature.

Want me to talk about your product? You can sponsor this site.

Related posts about ai: