Cost optimization strategies in Supabase - Time & Space Complexity
When using Supabase, it's important to understand how costs grow as you use more resources.
We want to see how the number of operations affects your spending over time.
Analyze the time complexity of querying and inserting multiple records.
const { data, error } = await supabase
.from('orders')
.select('*')
.limit(n);
for (let i = 0; i < n; i++) {
await supabase
.from('orders')
.insert([{ item: `item${i}`, quantity: 1 }]);
}
This code fetches a limited number of orders and then inserts new orders one by one.
Look at the repeated actions in this code.
- Primary operation: Inserting one order per loop iteration.
- How many times: Exactly n times, once for each new order.
As n grows, the number of insert calls grows the same way.
| Input Size (n) | Approx. Api Calls/Operations |
|---|---|
| 10 | 10 insert calls + 1 select call |
| 100 | 100 insert calls + 1 select call |
| 1000 | 1000 insert calls + 1 select call |
Pattern observation: The number of insert operations grows directly with n, while the select call stays the same.
Time Complexity: O(n)
This means the cost and time grow in a straight line as you add more records.
[X] Wrong: "Inserting many records one by one costs the same as inserting them all at once."
[OK] Correct: Each insert call uses resources and time, so many calls add up and increase cost.
Understanding how operations scale helps you design efficient and cost-friendly cloud apps.
"What if we batch all inserts into a single call? How would the time complexity change?"