Abuse Prevention: Making Scalping, Credential Stuffing, and Fake Accounts Unprofitable for Adversaries Who Adapt
System Design series · Part 8 Security (5 of 5)
- Authentication: Sessions, Tokens, OAuth 2.0/OIDC, and Where Login State Should Live
- Authorization Models and the OWASP API Top 10: What You Can Do After Logging In
- After BOLA Gets Past the BFF: How Microservices Pass Along Who Is Calling and for Whom
- Encryption in Transit and at Rest, and Secrets Management: What Encryption Protects Depends on Who Can Get the Key
- Abuse Prevention: Making Scalping, Credential Stuffing, and Fake Accounts Unprofitable for Adversaries Who Adapt
System Design series Part 8-5 | Previous: Encryption in Transit and at Rest, and Secrets Management | Next: URL Shortener | Series map
Read first: Part 6-4 Rate Limiting.
Scenario and problem
The annual talk from the series introduction: 3,000 seats, 50,000 people waiting online, and about 24,000 sign-up requests pouring in within 30 seconds of opening. After last year’s event, the operations team put together this list of problems:
- All the seats were gone within 4 seconds, and tickets resold at a markup showed up on social media right after. The sign-up records show that many accounts were registered only a week before opening and paid with the same credit card
- In the hour before opening, the login API’s failure rate jumped from the usual 3% to 60%, and 200 accounts were taken over
- New-member first-purchase discount codes were claimed in bulk, and most of the accounts that claimed them never did anything afterwards
- The SMS bill for phone verification codes spiked in a single night, with the recipient numbers concentrated in a few foreign number ranges
- The speaker list and talk content were copied wholesale by another website
- Full in 4 secondsAll the seats were gone within 4 seconds, and tickets resold at a markup showed up on social media right after. Many accounts were registered only a week before opening and paid with the same credit card.
- Credential stuffingIn the hour before opening, the login API's failure rate jumped from the usual 3% to 60%, and 200 accounts were taken over.
- Discount codes drainedNew-member first-purchase discount codes were claimed in bulk, and most of the accounts that claimed them never did anything afterwards.
- SMS bill spikesThe SMS bill for phone verification codes spiked in a single night, with the recipient numbers concentrated in a few foreign number ranges.
- Content copiedThe speaker list and talk content were copied wholesale by another website.
- Every request is legitimateEvery request has an account, is logged in, is well-formed, and stays within the rate limit. The adversary adapts: block one approach and they switch to another.
Every request is “legitimate” on its own: it has an account, is logged in, is well-formed, and stays within the rate limit. These problems map to API6 Unrestricted Access to Sensitive Business Flows in the OWASP API Security Top 10, and to the automated threats cataloged in OWASP “Automated Threats to Web Applications”: Scalping, Denial of Inventory, Credential Stuffing, Account Creation, and Scraping.
The difference from the Rate Limiting post: rate limiting protects capacity, and its target is traffic; abuse prevention faces an adversary who adapts, and its target is profit. Block one approach and they switch to another.
The simplest approach and its limits
Rate limit by IP and put a CAPTCHA on every form
- An IP no longer means one person: residential proxy networks offer millions of real home IPs, each sending only a few requests; conversely, NAT on corporate and mobile networks puts a thousand or more normal users behind one IP, and rate limiting by IP blocks them first
- CAPTCHAs cost attackers very little: public human CAPTCHA-solving services charge roughly a few US dollars or less per thousand solves (a rough estimate that varies by service). Reselling one talk ticket can make NT$1,000 or more, so the cost of solving one CAPTCHA is negligible
- Everyone pays the price: with a CAPTCHA on every action, the conversion rate of normal users drops, and users who rely on assistive technology may not be able to use the site at all
Core mechanism
Think in economics: make abuse unprofitable
Attackers do the math on cost too. The goal of abuse prevention is not to “block everything” but to make the cost of an attack higher than its payoff:
| Attack | Attacker’s payoff | Ways to raise the cost |
|---|---|---|
| Scalping | The resale markup on each ticket | Real-name, non-transferable tickets; a lottery instead of first come, first served |
| Credential stuffing | The value of a stolen account (stored balance, personal data, resellable tickets) | Breached-password checks, MFA, passkeys |
| Fake accounts claiming discounts | The discount amount per account | Tie the discount to a payment instrument or a real name, not to the account |
| SMS pumping | A cut of the SMS fees, shared with a carrier | Send limits per number and per country code |
| Scraping content | The copied content and lists | Login required for details; pagination limits; return only the fields needed |
Very often, changing the business flow works better than any detection technique.
The business flow is the strongest defense
First come, first served by its nature rewards whoever is fastest, and the fastest is always a bot. Switch popular talks to a lottery:
- Entries stay open for 24 hours, and submitting at any moment in that window counts the same; after the deadline, 3,000 people are drawn at random, and winners pay by a deadline
- The bots’ speed advantage is gone. The only way left for an attacker to raise their odds is more accounts, so the problem becomes “one person gets only one valid entry”: deduplicate by verified phone number, payment instrument, or real-name data
- The 24,000 requests at the moment of opening disappear too, and the load spreads evenly over 24 hours (the peak estimate from the Napkin Math post changes completely)
Where a lottery does not fit, there are other flow-level options:
- Virtual waiting room (Rate Limiting post): people who were already waiting before opening are let in in random order, not by the millisecond they arrived
- A cap on held seats: each account can hold only one seat at a time, a hold lasts 10 minutes, and it is released automatically when it expires (the timeouts from the Saga post). Hoarding seats without paying stops working
- Real names and non-transferable tickets: the ticket is tied to the registrant and checked at the door. A resold ticket cannot be used, so the scalper’s profit disappears
Signals across many dimensions, not just IP
| Dimension | Signals | Caveats |
|---|---|---|
| Network | IP reputation, whether it comes from a data center or a known proxy, the IPv6 /64 prefix | IPv6 users usually own an entire /64, and an attacker can rotate addresses inside it endlessly, so count IPv6 per /64 |
| Client | Browser challenges (such as Cloudflare Turnstile), device attestation in the app | Can be bypassed, but raises the cost of large-scale automation |
| Account | Account age, whether it is verified, past behavior, whether MFA is enabled | A burst of new accounts right before a popular event is itself a signal |
| Behavior | Actions per minute, the order of actions (calling the sign-up API directly without viewing the talk page first) | Normal users behave in many different ways too, so tune thresholds on real data |
| Business | The same card, phone number, or shipping address tied to several accounts | Hardest to fake, because each one costs money to obtain |
Any single signal can be bypassed or can misfire; only in combination are they reliable. The same goes for rate-limit keys: count by account, device, network range, payment instrument, and target resource at the same time, with a global cap as well.
Step up checks by risk instead of putting a gate in front of everyone
Combine the signals into one risk judgment, and let the risk decide how much friction to add:
| Risk | Handling |
|---|---|
| Low (old account, verified, normal behavior) | Let it through |
| Medium (new account, data center IP, acting a bit fast) | Require a browser challenge or a CAPTCHA |
| High (known malicious IP, the same card already used on several accounts) | Require MFA or real-name verification; or reject outright and log it |
Most normal users never notice the protection at all; the friction lands on the suspicious requests.
Credential stuffing: do not defend with account lockouts
The signature of credential stuffing is that each account is tried only once or twice, so “lock the account after 5 failures” catches almost nothing. Worse, an attacker can deliberately enter wrong passwords for a victim’s account to get it locked, which turns into a denial of service against your users.
What works better:
- Look at the whole picture: the site-wide login failure rate, and how many different accounts one device or network range tries, rather than the failure count of a single account
- Breached-password checks: at login or when setting a password, check whether the password appears in known breach data. Have I Been Pwned’s Pwned Passwords API uses k-anonymity: you send only the first 5 characters of the password’s SHA-1 hash and match the returned list locally, so the service never learns the full hash
- Evaluate successful logins too: on the attempt where credential stuffing succeeds, the username and password are correct. Require step-up verification for successful logins from a new device or a new region, and notify the user
- The root fix: MFA and passkeys (Authentication post)
SMS pumping
Every “send a phone verification code” costs money. Attackers abuse the SMS verification in sign-up or login to send large volumes to high-rate numbers in specific countries, then take a share of the revenue from the carrier. A rough estimate: at a few NT dollars per international SMS, 100,000 sends triggered in one night make a bill of several hundred thousand NT dollars, and none of it shows up in ordinary error monitoring.
Defenses:
- Send limits per number, per number range, and per country code, plus a global hourly budget that triggers an alert and stops sending automatically when exceeded
- Enable SMS only for countries where you actually have business
- Pass a browser challenge before an SMS is sent, and require another step to be completed first (such as email verification)
- Wherever email, passkeys, or an authenticator app will do, do not use SMS
Detection and response is a loop
Abuse prevention is never “done”. What you need is a loop that can adjust quickly:
- Monitor business metrics: sign-ups per minute for each talk, new accounts per hour, SMS per country code, how fast discount codes are being claimed, the site-wide login failure rate (Observability post)
- Alert on anomalies: compare against the usual baseline, not only against fixed thresholds
- Switches you can flip right away: raise the friction on a flow without a deploy (for example, turn on challenges for all new accounts), or pause SMS to a country code
- Review afterwards: feed confirmed abuse cases back into the rules and thresholds
When responding, weigh the cost of a false positive: blocking outright tells the attacker immediately, so they adapt, and it also hits normal users; just lowering the privileges of suspicious accounts (for example, sending their sign-ups to manual review) buys time. Users who are flagged by mistake need a way to appeal.
Privacy
Device fingerprints, behavior logs, and IP locations are all personal data. Collect only the signals you actually use for protection, set retention periods, explain them in the privacy policy, and protect this data itself following the principles of the Encryption post.
Comparing options
| Option | Stops | Does not stop | Cost |
|---|---|---|---|
| Rate limiting by IP | Large volumes from a single source | Residential proxies, distributed botnets | Normal users behind NAT get blocked by mistake |
| CAPTCHAs and browser challenges | Cheap, large-scale automation | CAPTCHA-solving services, real people | Friction for users; accessibility problems |
| Risk-based step-up checks | Most automation, with the friction concentrated on suspicious requests | Advanced attacks that mimic normal behavior | Requires collecting signals and tuning the model and thresholds |
| Flow design (lottery, real names, caps) | Attacks such as scalping and hoarding that depend on speed and volume | Limited when fake identities are cheap | Changes the user experience; needs agreement from the business side |
| Commercial bot management services | Known bot signatures, signals at large scale | Attacks custom-built for your business | Fees; reliance on a third party; privacy concerns |
What the talk platform chose:
- Popular talks switch to a lottery, deduplicated by verified phone number; winners pay within 48 hours; tickets carry the attendee’s real name
- Regular talks stay first come, first served, but each account can hold only one seat at a time, for 10 minutes
- Rate limiting: counted separately by account, device, IPv4 address and IPv6 /64 range, and payment instrument
- Risk judgment: require Turnstile for new accounts, data center IPs, and abnormal speed; reject known malicious sources outright
- SMS: Taiwan phone numbers only, 5 messages per number per day, with a global hourly budget cap
- Login: breached-password checks, MFA for logins from new devices, monitoring of the site-wide failure rate
In Java
1. Multi-dimensional rate-limit keys
public final class AbuseKeys {
private AbuseKeys() {
}
/** IPv4 uses the full address; IPv6 takes the first 64 bits, because a user usually owns an entire /64. */
public static String network(InetAddress address) {
byte[] ip = address.getAddress();
if (ip.length == 4) {
return "ip4:" + address.getHostAddress();
}
return "ip6:" + HexFormat.of().formatHex(ip, 0, 8) + "/64";
}
/** Every counter to check when signing up for a talk; if any one is exceeded, reject or require step-up verification. */
public static List<RateLimitRule> forRegistration(long memberId, String deviceId, InetAddress ip, long lectureId) {
return List.of(
new RateLimitRule("reg:member:" + memberId, 5, Duration.ofMinutes(1)),
new RateLimitRule("reg:device:" + deviceId, 10, Duration.ofMinutes(1)),
new RateLimitRule("reg:net:" + network(ip), 30, Duration.ofMinutes(1)),
new RateLimitRule("reg:lecture:" + lectureId, 2_000, Duration.ofSeconds(1))); // protects a single talk's hot spot
}
}The counters reuse the Redis token bucket from the Rate Limiting post. ip must be a trusted source address: behind a load balancer, take it from the trusted proxy configuration instead of trusting the X-Forwarded-For the client sends.
2. Deciding by risk whether to require a challenge
public enum RiskDecision { ALLOW, CHALLENGE, DENY }
@Component
public class RegistrationRiskAssessor {
private final IpReputation ipReputation;
private final MemberProfileRepository members;
public RegistrationRiskAssessor(IpReputation ipReputation, MemberProfileRepository members) {
this.ipReputation = ipReputation;
this.members = members;
}
public RiskDecision assess(long memberId, InetAddress ip, Duration sinceLecturePageView) {
if (ipReputation.isKnownMalicious(ip)) {
return RiskDecision.DENY;
}
MemberProfile member = members.findById(memberId).orElseThrow();
int score = 0;
if (member.createdAt().isAfter(Instant.now().minus(Duration.ofDays(7)))) score += 2;
if (!member.phoneVerified()) score += 2;
if (ipReputation.isDatacenter(ip)) score += 2;
if (sinceLecturePageView.compareTo(Duration.ofSeconds(2)) < 0) score += 1; // submitted less than 2 seconds after seeing the page
return score >= 3 ? RiskDecision.CHALLENGE : RiskDecision.ALLOW;
}
}
@RestController
@RequestMapping("/v1/lectures/{lectureId}/entries")
public class LotteryEntryController {
private final RegistrationRiskAssessor risk;
private final TurnstileVerifier turnstile;
private final LotteryService lottery;
public LotteryEntryController(RegistrationRiskAssessor risk, TurnstileVerifier turnstile, LotteryService lottery) {
this.risk = risk;
this.turnstile = turnstile;
this.lottery = lottery;
}
@PostMapping
public ResponseEntity<Void> enter(@PathVariable long lectureId, @RequestBody EntryRequest request,
@AuthenticationPrincipal Jwt jwt, HttpServletRequest http) {
long memberId = CurrentMember.from(jwt).memberId();
InetAddress ip = InetAddresses.trustedClientAddress(http);
switch (risk.assess(memberId, ip, request.sinceLecturePageView())) {
case DENY -> throw new ResponseStatusException(HttpStatus.FORBIDDEN);
case CHALLENGE -> {
if (request.turnstileToken() == null || !turnstile.verify(request.turnstileToken(), ip, "lottery-entry")) {
// tell the frontend to show a challenge instead of failing outright
return ResponseEntity.status(HttpStatus.FORBIDDEN).header("X-Challenge-Required", "turnstile").build();
}
}
case ALLOW -> { }
}
lottery.enter(lectureId, memberId);
return ResponseEntity.accepted().build();
}
}sinceLecturePageViewcomes from the client and can be forged, so it is only one of the signals that add to the score; it can never decide on its own to let a request through- For Turnstile’s server-side verification (
action, hostname, replay protection), see Cloudflare Turnstile in Practice - Tune the scores and thresholds on real data; launch first in a “log only, do not block” mode and watch the false positive rate
3. Lottery: one verified identity gets one entry
CREATE TABLE lottery_entry (
lecture_id BIGINT NOT NULL,
member_id BIGINT NOT NULL,
verified_phone BINARY(32) NOT NULL, -- HMAC of the phone number (the blind index from the Encryption post)
created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
result VARCHAR(10) NULL, -- WON or LOST, filled in after the draw
PRIMARY KEY (lecture_id, member_id),
UNIQUE KEY uk_lecture_phone (lecture_id, verified_phone)
);@Service
public class LotteryDraw {
private final JdbcClient jdbc;
public LotteryDraw(JdbcClient jdbc) {
this.jdbc = jdbc;
}
/** Run once by a batch job after entries close. */
@Transactional
public void draw(long lectureId, int seats) {
List<Long> entrants = jdbc.sql("SELECT member_id FROM lottery_entry WHERE lecture_id = :id AND result IS NULL")
.param("id", lectureId)
.query(Long.class)
.list();
Collections.shuffle(entrants, new SecureRandom()); // unpredictable, and not affected by the order of entries
List<Long> winners = entrants.subList(0, Math.min(seats, entrants.size()));
jdbc.sql("UPDATE lottery_entry SET result = IF(member_id IN (:winners), 'WON', 'LOST') WHERE lecture_id = :id AND result IS NULL")
.param("winners", winners.isEmpty() ? List.of(-1L) : winners)
.param("id", lectureId)
.update();
}
}uk_lecture_phonelets each verified phone number enter only once, so to raise their odds an attacker has to obtain more real phone numbers- Loading 50,000 entries into memory at once and shuffling them is no problem; an
INlist of 3,000 values is something MySQL can handle, but at a larger scale you should split it into batches or use a temporary table - The draw runs only once, and once the results are written it cannot be redrawn; write both the run and the results to the audit log, to prevent manipulation by insiders
The code above is written from the official documentation of Spring Boot 4.1, Spring Security 7.1, and the Java standard library, and has not been compiled or run.
IpReputation,TurnstileVerifier, andInetAddresses.trustedClientAddressare illustrative components.
Pitfalls and gotchas
- Judging by IP alone: it blocks normal users behind NAT and misses residential proxies
- Trusting
X-Forwarded-For: the attacker adds this header themselves, and every request looks like it comes from a different IP. Use only the value added by a trusted proxy - Locking accounts: it does not stop credential stuffing, and instead lets the attacker lock anyone out
- CAPTCHAs for everyone: the conversion rate of normal users drops, while attackers get around them with solving services
- Protection only on the frontend: the challenge runs only on the web page, not on the app’s API or the older API versions (OWASP API9)
- Error messages that leak the rules: “You have tried 5 times in the last minute” tells the attacker the threshold, so they just try 4 times a minute
- No SMS budget cap: you find out when the bill arrives
- Rule changes need a deploy: an attack is under way, yet adjusting a threshold has to go through the full deployment pipeline
- Ignoring false positives: the blocking rules keep piling up, customer support starts getting complaints from normal users who cannot sign up, and nobody knows which rule is responsible
Attack scenarios
| Attack | How it happens | Defense |
|---|---|---|
| Scalping | Bots grab every seat the moment sign-ups open, then resell them at a markup | Lottery; real names and non-transferable tickets; deduplicate by verified identity |
| Denial of Inventory | Holding large numbers of seats without paying, so others cannot sign up | A per-account hold cap; short hold periods; a sign-up counts only once it is paid |
| Credential Stuffing | Mass login attempts with leaked credentials, only once or twice per account | Site-wide failure rate monitoring; breached-password checks; step-up verification for new devices; MFA and passkeys |
| Mass account creation | Registering many accounts with disposable emails to claim new-member offers | Tie offers to a payment instrument or a verified phone number; unlock new accounts’ privileges gradually |
| SMS pumping | Triggering verification codes sent to high-rate numbers | Caps per number, number range, and country code; a global budget; limit the countries SMS is enabled for |
| Scraping | Copying talk and speaker data automatically | Login required for details; pagination and rate caps; return only the fields needed |
| Carding | Testing large numbers of stolen credit cards with small charges through the payment API | Per-card and per-account payment failure caps; enable 3-D Secure; hand it to the payment provider’s fraud controls |
| CAPTCHA farms | Forwarding challenges to real people to solve | Do not rely on challenges alone; combine them with account and business signals |
| Spoofed source IP | Sending a fake X-Forwarded-For |
Trust only addresses added by trusted proxies |
When to use it, and when not to
- Always do it: every flow that involves money, scarce resources (seats, discounts), account security, or sending costs (SMS, email) needs an abuse threat model and monitoring
- Change the flow first: lotteries, real names, and caps are often cheaper and more effective than detection techniques
- Use risk-based step-up: when you have many users and cannot add friction for everyone
- Use a commercial bot management service: when the attackers’ scale and skill exceed what the team can handle on its own, and the business losses are large enough to pay for it
- Do not over-protect: for flows with no scarce resources and no monetary value (such as browsing the public list of talks), basic rate limiting is enough; too much protection hurts normal users
References
- OWASP Automated Threats to Web Applications (OAT Handbook): https://owasp.org/www-project-automated-threats-to-web-applications/
- OWASP API Security Top 10 2023 — API6 Unrestricted Access to Sensitive Business Flows: https://owasp.org/API-Security/editions/2023/en/0xa6-unrestricted-access-to-sensitive-business-flows/
- OWASP Cheat Sheet Series — Credential Stuffing Prevention: https://cheatsheetseries.owasp.org/cheatsheets/Credential_Stuffing_Prevention_Cheat_Sheet.html
- Have I Been Pwned — Pwned Passwords API (k-anonymity range search): https://haveibeenpwned.com/API/v3#PwnedPasswords
- NIST SP 800-63B Rev. 4 — Rate Limiting (Throttling): https://pages.nist.gov/800-63-4/sp800-63b/authenticators
- Cloudflare Turnstile Documentation: https://developers.cloudflare.com/turnstile/
- Interactive diagrams: Dilum Sanjaya, System Design — an interactive course: https://designed-to-scale.vercel.app/
Comments