All blogs

Security · · 18 min read

Your APIs Are Secure. But Is Your Application?

Designing a resilient backend against distributed bot networks, automated account creation and authenticated API abuse.

Raviteja Salva

Stage 1: The blind spot

Everything looks secure

Imagine you have built a public-facing application where anyone can create an account, log in and start using its features.

Your backend has two public endpoints:

  • POST /auth/register — Allows anyone to create an account using an email address and password.
  • POST /auth/login — Allows registered users to authenticate using their credentials and receive an access token and a refresh token.

Every business API is protected and requires a valid access token. The token refresh operation requires a valid refresh token.

You have implemented secure password hashing, JWT authentication, refresh token rotation, authorization guards and input validation.

The application flow is straightforward:

  1. A user registers with an email address and password.
  2. The backend creates a user account in the database.
  3. The user logs in using the registered credentials.
  4. The backend validates the credentials and issues tokens.
  5. The user uses the access token to access protected APIs.
  6. When the access token expires, the user can obtain a new one using the refresh token.

Everything works as expected.

Unauthorized users cannot access protected endpoints. Invalid credentials are rejected. Expired access tokens are not accepted.

From an authentication and authorization perspective, everything looks secure.

But is your application actually secure?

What if the attacker doesn't need to hack anything?

If you have ever used Instagram or Telegram, you have probably encountered bot accounts.

There are automated systems capable of creating and operating enormous numbers of digital identities with minimal human intervention.

Now imagine someone with access to such a system discovers your application.

The attacker doesn't have a database of your existing users' credentials. They haven't stolen anyone's password. They haven't discovered a vulnerability in your JWT implementation.

They don't need any of that.

Your registration endpoint is publicly accessible because your application is designed to allow anyone to create an account.

The attacker creates large numbers of dummy accounts, each with its own email address and password, through your registration endpoint.

These accounts are then authenticated through your login endpoint using the credentials they registered with.

Your backend validates those credentials and issues legitimate access tokens and refresh tokens.

From your application's perspective, these are successfully registered and authenticated users.

They can now access the features available to ordinary users.

To complicate the situation further, the traffic originates from a distributed network of machines with different IP addresses.

Your application begins experiencing increasing CPU utilization, database connection exhaustion, memory consumption, growing background job queues and eventually service unavailability.

What the logs showPOST/auth/register203.0.113.18201POST/auth/login198.51.100.42200GET/reports192.0.2.7200POST/auth/register203.0.113.201201POST/auth/login198.51.100.9200

Registered accounts, correct credentials, legitimate tokens. Every request passes.

What the server feels503Service
Unavailable
CPU97%DB connections100 / 100Memory91%Job queuegrowing

Together, the same requests exhaust CPU, database connections, memory and job queues.

Nothing is bypassed. Every request is valid, and the combined load is not.

The attacker hasn't bypassed your authentication system.

They are using your application exactly as you designed it to be used, but at a scale and frequency you never intended.

This is a combination of automated account creation, coordinated multi-account abuse, unrestricted resource consumption and application-layer distributed denial-of-service attacks.

How do you defend your application against something like this?

Stage 2: The obvious fixes

Attempt 1IP-based rate limiting

The first solution that probably comes to your mind is rate limiting.

You introduce a restriction on the number of requests an IP address can make within a specific time window.

Once the limit is exceeded, your backend returns a 429 Too Many Requests response.

You apply this protection to your registration endpoint, login endpoint and protected APIs.

This works reasonably well when excessive traffic originates from a limited number of sources.

But does it solve your problem?

The attacker operates through a distributed network with numerous IP addresses. Even when individual sources remain within their permitted limits, their combined traffic can exceed your application's capacity.

There is another problem.

Imagine hundreds of employees accessing your application from the same corporate network. Many of them could share a single public IP address.

Aggressive IP-based restrictions could end up blocking genuine users.

Does it work?

  • Yes, against certain types of excessive traffic.
  • But it cannot independently protect your application against large-scale distributed abuse.

Attempt 2User-based rate limiting

Since IP addresses are not reliable representations of individual users, you decide to introduce user-based rate limiting.

Every protected API already requires an access token. You can extract the authenticated user's identity from the validated token and enforce a request quota against that account.

You introduce Redis to maintain distributed rate-limiting counters across multiple backend instances.

This prevents an individual account from consuming unlimited resources, regardless of which backend instance processes its requests.

But remember how your application works.

Anyone can register.

The attacker controls an enormous number of accounts, each with its own identity and valid access token.

Even if individual accounts respect their allocated quotas, their combined resource consumption can exceed your application's capacity.

User-based rate limiting also does not directly protect your registration endpoint because an account does not yet exist when registration begins.

Does it work?

  • Yes, it restricts individual account abuse.
  • But it does not independently solve mass account creation or coordinated multi-account abuse.

Attempt 3Email verification

What if you prevent users from logging in until they verify their email addresses?

You modify the registration flow so that newly created accounts must complete email verification before gaining access to protected features.

This introduces an additional barrier to automated account creation.

You could also introduce disposable email detection, email domain reputation checks and registration frequency monitoring.

However, email verification has a fundamental limitation.

It proves that someone controls an email address. It does not prove that the account belongs to a unique human being.

Automated accounts with access to functioning mailboxes can still become verified accounts.

Additionally, you have introduced another resource that needs protection: your email delivery service.

Excessive registration and verification requests could consume email provider quotas, increase operational costs and delay verification emails for genuine users.

You would also need to introduce verification request limits, resend cooldowns and restrictions on unverified accounts.

Does it work?

  • Yes, it increases the difficulty and cost of automated account creation.
  • But a verified email address is not proof of human identity.

Attempt 4CAPTCHA

What if you introduce CAPTCHA before allowing someone to register?

You integrate a service such as Cloudflare Turnstile into your registration and login flows.

Before processing suspicious requests, your backend validates the challenge response.

This helps reduce automated traffic before your application performs expensive operations such as password hashing, account creation and database writes.

But CAPTCHA is not an absolute guarantee that every account belongs to a genuine human.

There is also a user experience problem.

If you introduce challenges on every login attempt or sensitive operation, genuine users may find your application frustrating to use.

Instead of challenging everyone unnecessarily, you could introduce adaptive challenges based on risk.

Normal users experience minimal friction, while suspicious activity triggers additional verification.

Does it work?

  • Yes, it helps reduce automated abuse.
  • But it should be treated as one layer of protection rather than a complete solution.

Attempt 5Device fingerprinting

If IP addresses are unreliable and accounts can be created in large numbers, perhaps identifying devices could help.

Device fingerprinting uses browser characteristics, operating system information, session attributes and other signals to identify potentially related activity.

This could help your application detect suspicious relationships between multiple accounts.

However, device fingerprints are not permanent or guaranteed to be unique.

Genuine users might share devices, change browsers, update their operating systems or use privacy-focused browser configurations.

There are also privacy implications associated with collecting device information.

You should therefore treat device fingerprints as additional risk signals rather than definitive proof of malicious activity.

Blocking someone solely because their device resembles another suspicious device could create unnecessary false positives.

Does it work?

  • Yes, it provides additional context for abuse detection.
  • But it is not a reliable standalone identity or blocking mechanism.

Attempt 6Scaling your infrastructure

Your application is crashing because it cannot handle the incoming traffic.

Why not simply increase its capacity?

You move your application to Kubernetes and configure horizontal autoscaling.

Whenever resource utilization increases, Kubernetes can create additional application replicas to distribute the workload.

This improves your application's ability to handle legitimate traffic spikes.

But autoscaling does not distinguish between genuine demand and malicious demand.

As excessive traffic continues, your infrastructure could continue scaling until it reaches its configured limits.

Even if your application remains available, your infrastructure costs could increase significantly.

This introduces another threat known as Economic Denial of Sustainability, or EDoS.

An attacker doesn't necessarily need to make your application unavailable. Causing an unsustainable increase in operational costs can also be damaging.

Furthermore, increasing the number of API replicas does not automatically increase database capacity, email provider quotas or background processing capabilities.

Eventually, another component becomes the bottleneck.

Does it work?

  • Yes, it increases your application's capacity and improves availability.
  • But scaling is a capacity management strategy, not an abuse prevention strategy.

Attempt 7Introducing a Web Application Firewall

Until now, most of your security mechanisms have been implemented inside your application.

But every malicious request that reaches your backend has already consumed some infrastructure resources.

What if you could reject suspicious traffic before it reaches your application?

You introduce an edge protection layer using a service such as Cloudflare.

Depending on the configuration and available features, this can provide:

  • Distributed denial-of-service protection.
  • Web Application Firewall rules.
  • Bot management.
  • Network reputation analysis.
  • Traffic restrictions.
  • Adaptive challenges.

You also ensure that your origin server cannot be accessed directly in a way that bypasses this protection.

This reduces unnecessary traffic reaching your infrastructure.

However, a generic firewall does not necessarily understand your application's business logic.

A request to generate a complex analytics report might look perfectly legitimate from a network perspective, even though the account requesting it is consuming an unreasonable amount of computational resources.

Your application has access to business-specific information that an external firewall may not have.

Account history, registration patterns, feature usage, resource consumption and previous suspicious activity are all valuable signals.

Does it work?

  • Yes, it provides valuable perimeter protection.
  • But you still need application-level abuse prevention.

Stage 3: Defence in depth

You are trying to solve the wrong problem

After evaluating all these approaches, you might realize that you have been focusing too much on identifying the attacker.

You have been trying to answer one question:

How do you identify and block every bot accessing your application?

But what if you cannot reliably distinguish every automated account from a genuine user?

What if every request is technically valid?

What if the attacker has more accounts, machines and computational resources than you anticipated?

Perhaps you should also be asking a different question.

How do you ensure that your application survives even when you cannot distinguish an attacker from a legitimate user?

This changes the way you approach your entire security architecture.

Instead of depending entirely on identifying malicious users, you need to control how much of your infrastructure any account, group of accounts or incoming workload is allowed to consume.

Building a defence-in-depth architecture

There is no single solution to this problem.

Instead, you need multiple independent layers of protection. Each layer should address a specific weakness, and the failure of one mechanism should not result in the failure of your entire application.

Protecting the registration endpoint

The registration endpoint is where the problem begins.

Every successful registration can consume multiple resources, including password hashing, database writes, storage, email delivery and account initialization.

If your application performs expensive initialization operations for every newly registered account, automated registrations can become particularly damaging.

You should introduce registration-specific rate limits, adaptive challenges, email reputation checks and global registration capacity controls.

You should also avoid provisioning unnecessary resources immediately after registration.

Where appropriate, expensive account initialization can be deferred until verification or actual feature usage.

Unverified accounts can have a defined expiration and cleanup policy.

The objective is to reduce the resource cost of account creation and prevent uncontrolled registration activity from overwhelming your infrastructure.

Protecting the login endpoint

Even if an account has already been registered, logging in is not a computationally free operation.

Your backend needs to retrieve the account, verify its password and issue authentication tokens.

Secure password hashing algorithms are intentionally computationally expensive.

Under excessive authentication traffic, password verification alone can become a significant source of CPU and memory consumption.

You should introduce login-specific rate limits, bounded password verification concurrency, request timeouts and risk-based challenges.

These protections should operate before expensive authentication work whenever possible.

You should not weaken your password hashing configuration simply to accommodate excessive traffic.

Instead, control how much authentication work your infrastructure accepts at any given time.

Progressive account trust

A newly registered account should not automatically receive the same resource consumption privileges as an established, trusted account.

You can introduce a progressive account trust system.

New accounts start with reasonable restrictions on expensive operations.

Verified accounts receive standard initial quotas.

Accounts demonstrating legitimate usage can gradually receive additional privileges.

Suspicious accounts can be subjected to additional verification, reduced quotas or temporary restrictions.

Confirmed abusive accounts can be suspended, with their active sessions revoked.

However, trust should not depend solely on account age or email verification.

It should consider multiple signals, including usage history, account behaviour and previous security events.

The objective is to make mass account creation less effective as a means of consuming application resources.

Multi-dimensional rate limiting

Instead of relying on a single rate-limiting mechanism, combine several dimensions.

  • IP-based rate limiting.
  • Account-based rate limiting.
  • Session-based rate limiting.
  • Registration-specific limits.
  • Login-specific limits.
  • Endpoint-specific limits.
  • Global application-level limits.

Redis can maintain distributed rate-limiting state across multiple application replicas.

These limits should be enforced atomically so that concurrent requests cannot incorrectly exceed their allocated quotas.

Temporary rate-limiting data should expire automatically. You should also bound the amount of tracking state so that Redis itself does not become another resource exhaustion bottleneck.

You need a defined failure policy for situations where Redis becomes unavailable. Sensitive operations should not automatically receive unlimited access simply because the rate limiter has failed.

The actual thresholds should be determined through load testing and legitimate usage patterns rather than arbitrary assumptions.

No individual identifier needs to be perfect because the protection comes from combining multiple independent controls.

Cost-based rate limiting

One of the biggest limitations of traditional rate limiting is that it treats every request equally.

Consider five different operations in your application:

Illustrative resource cost
  • Fetch user profile1 unit
  • Update user profile2 units
  • Search database records10 units
  • Upload and process an image25 units
  • Generate an analytics report50 units

These values are illustrative, but they demonstrate an important concept.

Fetching a user profile is not computationally equivalent to generating a complex analytics report.

If both operations consume the same rate-limiting quota, your system does not accurately account for their impact on infrastructure.

Instead of allocating a fixed number of requests, allocate a resource consumption budget.

Expensive operations consume more of that budget, while lightweight operations consume less.

The weights should be based on measured CPU utilization, database workload, memory consumption and external service costs.

You should also enforce pagination limits, maximum upload sizes, query complexity restrictions and execution timeouts.

Rate limiting should not just count requests. It should account for their cost.

Global capacity protection

This is arguably the most important part of the architecture.

Regardless of how many accounts, IP addresses or devices are involved, your application must understand its maximum sustainable workload.

You need to introduce global admission controls, concurrent request limits, bounded queues, database connection limits and execution timeouts.

Once your system approaches its capacity, it should stop accepting additional work that it cannot safely process.

This is known as load shedding.

Instead of allowing requests to accumulate until your server crashes, your application deliberately rejects excess traffic.

Requests exceeding their allocated quotas receive a 429 Too Many Requests response.

Requests that cannot be processed because of temporary capacity exhaustion can receive a 503 Service Unavailable response.

However, a global limit alone introduces another problem.

Excessive traffic could consume the available capacity before genuine users get an opportunity to access the application.

To address this, you can introduce fair resource allocation, workload prioritization and reserved capacity for essential operations.

For example, registration traffic should not be allowed to consume every resource required by existing authenticated users.

The objective is not simply to keep your server running. It is to keep your application useful for genuine users.

A controlled rejection is better than an uncontrolled outage.

Behaviour-based abuse detection

Instead of evaluating every request independently, analyse broader patterns across your application.

Unusual registration growth, correlated account activity, abnormal feature usage, excessive resource consumption and suspicious session behaviour could indicate coordinated abuse.

A risk assessment system can combine these signals to determine whether additional restrictions are necessary.

Depending on the risk level, your application could allow normal access, introduce additional verification, temporarily reduce resource quotas or revoke sessions.

This does not necessarily require artificial intelligence or machine learning.

A well-designed rule-based system combined with statistical analysis and proper monitoring can provide a strong starting point.

More sophisticated detection mechanisms can be introduced later when sufficient behavioural data becomes available.

Isolating critical application resources

Imagine your registration endpoint, login endpoint, business APIs and background workers all share the same computational resources and database connection pool.

A massive increase in registration or authentication requests could consume resources required by every other feature.

Even users who are already authenticated could lose access to your application.

To prevent this, introduce resource isolation using the Bulkhead Pattern.

Registration and authentication workloads, business APIs and background workers should have independently controlled resources.

Database connection pools should be bounded, with capacity allocated according to workload requirements.

Password hashing and verification should have controlled concurrency.

Background jobs should have bounded queues, controlled retries and execution limits.

Shared infrastructure, such as the database, must also have its own capacity protections.

This reduces the likelihood that an overloaded component brings down unrelated components.

Resource isolation does not necessarily require converting your entire application into microservices. The appropriate level of isolation depends on your architecture and operational requirements.

Securing the session lifecycle

JWT access tokens are useful for authentication, but possessing a valid token should not grant unrestricted access indefinitely.

You should use short-lived access tokens, refresh token rotation, refresh token reuse detection and server-side session management.

If an account is identified as abusive, your application should be able to revoke its sessions and prevent further token refreshes.

Since already-issued JWT access tokens may remain valid until expiration, sensitive operations may require additional account-status or session-revocation checks.

The refresh endpoint itself should also be protected by rate limiting and resource controls.

Authentication security and abuse prevention must work together throughout the entire session lifecycle.

Protecting operational costs

A successful defence should protect your business as well as your application.

Configure maximum Kubernetes replica limits, infrastructure budget alerts, third-party API quotas, email delivery restrictions, storage quotas and bounded background job retries.

Autoscaling should operate within defined infrastructure and financial boundaries.

If a particular feature depends on an expensive external service, its consumption should be monitored and restricted independently.

Budget alerts alone do not prevent spending. Where supported, enforce actual consumption limits and define graceful degradation policies.

Your application should temporarily restrict non-essential operations when necessary instead of continuing to consume resources without limits.

An application that remains online but generates an unsustainable infrastructure bill has not been adequately protected.

The final architecture

Your proposed architecture now introduces multiple layers between incoming traffic and the underlying infrastructure.

Every incoming request first passes through edge-level protection, where suspicious traffic can be evaluated before reaching your origin server.

An API gateway enforces admission controls, request restrictions and distributed rate limits.

From there, requests follow different paths depending on the endpoint.

Registration requests pass through registration-specific limits, adaptive challenges, email validation and account creation capacity controls.

Login requests pass through authentication-specific limits, risk assessment and bounded password verification.

Protected API requests pass through JWT validation, account-status checks, account trust evaluation, authorization and cost-based resource quotas.

Token refresh requests pass through refresh token validation, session checks, rotation and refresh-specific limits.

Global capacity controls determine whether the relevant workload can safely accept additional work before expensive processing begins.

Finally, isolated application services, bounded database connection pools and controlled background workers process the accepted requests.

Monitoring and abuse detection operate across all these layers.

  1. Incoming trafficgenuine and automated, all of it valid
  2. 01Edge protectionCloudflareDDoS mitigationWAF rulesBot managementAdaptive challenges
  3. 02API gatewayRedis-backed limitsAdmission controlRequest restrictionsDistributed rate limits
  4. 03A path for each endpoint
    • RegistrationPOST /auth/register
      • Registration limits
      • Adaptive challenges
      • Email validation
      • Creation capacity
    • LoginPOST /auth/login
      • Login limits
      • Risk assessment
      • Bounded password verification
    • Protected APIsaccess token
      • JWT validation
      • Account status
      • Account trust
      • Authorization
      • Cost-based quotas
    • Token refreshrefresh token
      • Token validation
      • Session checks
      • Rotation
      • Refresh limits
  5. 04Global capacity controls429 and 503 by designLoad sheddingBackpressureFair workload allocation
  6. 05Isolated resourcesKubernetes, within limitsAuthenticationBusiness APIsBackground workersBounded database pools
Monitoring and abuse detectionacross every layer
The layers between incoming traffic and the infrastructure.

Your architecture would include:

  • Cloudflare for edge protection, WAF and DDoS mitigation.
  • An API gateway for traffic management and admission control.
  • Redis for distributed rate limiting and temporary security state.
  • Dedicated registration and authentication protections.
  • Authentication and authorization guards for identity and permissions.
  • A risk assessment system for account trust and behavioural analysis.
  • Cost-based quotas for application resource consumption.
  • Backpressure, load shedding and fair workload allocation.
  • Isolated resources for authentication, business APIs and background jobs.
  • Kubernetes for controlled horizontal scaling.
  • Monitoring and alerting for security, performance and operational costs.

Each layer addresses a different part of the problem.

If one layer fails to identify malicious activity, the remaining layers continue protecting your application.

Stage 4: Proving it

How do you know whether this actually works?

Implementing security mechanisms is not enough.

You need to validate whether they actually work under realistic conditions.

You can use Artillery, a load-testing tool, to evaluate your application in an isolated and authorized testing environment using synthetic accounts and controlled workloads.

Start by establishing a baseline for normal application usage.

Then progressively evaluate different scenarios.

Test scenarioWhat you need to validate
Normal application usageBaseline performance and user experience
Registration traffic spikesAccount creation capacity and database protection
Login traffic spikesPassword verification and CPU protection
Authenticated multi-account trafficDistributed quotas and global capacity controls
Expensive API operationsCost-based resource restrictions
Token refresh traffic spikesSession management capacity
Genuine and simulated abusive trafficFair resource allocation
Redis unavailabilityRate limiter failure handling
Database saturationBackpressure and resource isolation
Sustained excessive trafficAvailability and operational cost protection

One of the most important tests involves genuine user traffic and simulated abusive traffic occurring simultaneously.

You don't want to build a security system that successfully rejects excessive traffic but also makes your application unusable for genuine users.

During these tests, monitor:

  • CPU and memory utilization.
  • Database connection pool utilization.
  • Redis memory consumption.
  • Registration and authentication success rates.
  • Request rejection rates.
  • Genuine user success rates.
  • API response times, including p95 and p99 latency.
  • Background job queue sizes.
  • False-positive rates.
  • Infrastructure costs.
  • Recovery time after excessive traffic subsides.

Based on these observations, adjust your rate-limiting thresholds, resource budgets, concurrency limits and scaling policies.

The success criteria should not simply be whether your server remains online.

Your application should continue providing an acceptable level of service to genuine users, recover predictably and remain within its operational budget.

These are proposed validation criteria. The actual effectiveness of this architecture would need to be established through testing.

The takeaway.

What this changes about how you think about security

Authentication tells you which identity is making a request.

Authorization tells you what that identity is permitted to do.

Rate limiting tells you how frequently those operations can be performed.

Resource management tells you how much infrastructure those operations are allowed to consume.

Abuse detection helps you understand whether that behaviour is suspicious.

Resilience determines whether your application can survive when those protections are not enough.

These are different responsibilities, and none of them can completely replace the others.

A registered account does not mean you have acquired a genuine user.

A verified email address does not mean the user is human.

A valid JWT does not mean the user is trustworthy.

A successful CAPTCHA does not guarantee legitimate intentions.

And a horizontally scalable application is not necessarily a secure application.

Final thoughts

Security is often associated with preventing unauthorized access, protecting sensitive information and securing communication between systems.

But availability is also a fundamental part of security.

Your application might have perfect authentication, strong authorization, encrypted communication and securely hashed passwords.

Yet someone could still bring it down without exploiting a single authentication vulnerability.

They simply register, log in and use the features you have made available.

That is why securing your endpoints is not the same as securing your application.

No architecture can guarantee uninterrupted availability against an arbitrarily large attack. However, a well-designed system can reduce the impact, protect critical resources, control operational costs and recover predictably.

You need to build an application that understands its own limits and protects itself regardless of who is consuming its resources.

The goal is not to build a system that nobody can attack. The goal is to build a system that remains useful even while it is being attacked.

Raviteja SalvaFull Stack DeveloperLet's talk
Keep readingAll blogs
Contact

Let's build something remarkable.

Have a role, a project, or a hard problem worth talking through? Email is the fastest way to reach me, and everything else below works too.

Available for full-time roles
ResponseWithin 24 hours
LocationPune, India · IST
Work modeRemote / relocation

Open to full-time engineering roles, contract work, and technical conversations. No pitch necessary; a few lines about what you're building is enough.