Webhook registration endpoint in Rest API - Time & Space Complexity
When building a webhook registration endpoint, it is important to understand how the time it takes to process requests grows as more data is handled.
We want to know how the server's work changes when many webhook registrations happen.
Analyze the time complexity of the following code snippet.
POST /register-webhook
receive webhook_url
if webhook_url already in database:
return "Already registered"
else:
save webhook_url to database
return "Registration successful"
This code checks if a webhook URL is already registered and saves it if not.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Searching the database for the webhook URL.
- How many times: Once per registration request, but the search time depends on how many URLs are stored.
As the number of registered webhook URLs grows, the time to check if a URL exists changes.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The time to find a URL grows roughly in direct proportion to the number of stored URLs.
Time Complexity: O(n)
This means the time to process a registration grows linearly with the number of registered webhook URLs.
[X] Wrong: "Checking if a webhook URL exists is always fast and constant time."
[OK] Correct: If the database search is not optimized, it can take longer as more URLs are stored, making the check slower.
Understanding how your endpoint scales with more data shows you can build reliable and efficient APIs, a key skill in real projects.
"What if we used a hash table or index to store webhook URLs? How would the time complexity change?"