One of the more interesting backend engineering problems I've encountered recently wasn't about detecting spam. My application was already detecting it, yet suspicious submissions were still reaching users and triggering email notifications.
The problem surfaced while I was building Formgrid.dev, my SaaS product that provides developers and businesses with an open-source form backend, a visual form builder, and a built-in lead management system.
What initially appeared to be a spam detection problem turned out to be a much broader engineering problem. Improving the detection rules alone wouldn't have been enough. I needed to understand how the entire submission pipeline worked, from the moment an HTTP request reached the server to the point where notifications and integrations were triggered.
The idea behind the form backend is simple. Developers connect their HTML forms or frontend applications to an endpoint, and Formgrid.dev handles everything that happens after a visitor submits a form: storing the submission, sending email notifications, managing leads, triggering webhooks, and synchronizing data with external services such as Google Sheets and Notion.
This means developers can build functional contact forms, enquiry forms, and lead generation forms without having to build and maintain their own backend infrastructure.
But when you expose public endpoints that accept arbitrary user input, you inherit a problem that almost every form backend eventually has to deal with: automated spam.
Some submissions contained financial reward claims, suspicious URLs embedded in name fields, randomly generated email addresses, and values that made little sense in the context of the form.
What made this particularly interesting was that the platform's AI classification system was already identifying these submissions as likely spam. Yet they were still appearing in customers' lead pipelines and triggering email notifications.
From a customer's perspective, a system that tells you something is spam but still delivers it to your inbox hasn't really solved the problem.
I needed to understand why that was happening, how the existing spam protection worked, and how to improve it without accidentally blocking legitimate customer enquiries.
This post walks through the engineering behind that investigation, the architectural decisions I made, and the lessons I learned about building reliable spam protection for public-facing APIs.
The real cost of spam in a SaaS application
Spam is easy to think of as an inconvenience. Someone submits unwanted content, the recipient deletes it, and life goes on.
But in a SaaS application that processes form submissions on behalf of other businesses, the consequences extend beyond an untidy inbox.
A single form submission can trigger several operations:
- A database write.
- An email notification to the form owner.
- An automated response to the submitter.
- An AI classification request.
- A webhook to an external application.
- A synchronization operation with Google Sheets, Notion, or another integration.
- Additional background processing.
The application doesn't necessarily know whether the submission represents a potential customer or an automated bot. Unless the submission pipeline makes that distinction early enough, both are treated as legitimate events.
Consider a hypothetical application receiving 10,000 spam submissions. If each submission triggers five downstream operations, that's potentially 50,000 unnecessary operations.
The cost isn't just database storage. It includes email delivery, external API requests, background processing, AI inference, and infrastructure resources.
There's also a cost that is harder to measure: customer trust.
A business using a form backend expects to receive enquiries from potential customers, not spend time filtering fraudulent financial messages and suspicious links.
At the same time, incorrectly blocking a legitimate submission could mean that a business loses a potential customer without ever knowing that the enquiry existed.
That creates an interesting engineering constraint. The objective isn't simply to maximize the number of spam submissions detected. It's to reduce unwanted submissions while preserving legitimate ones.
Those are two different problems, and optimizing for one without considering the other can make the product worse.
Why detecting spam wasn't enough
Formgrid.dev already had an AI-powered classification system that could categorize incoming submissions based on their content.
A submission could be classified as a hot lead, a support request, a sales pitch, or likely spam.
This was useful for helping customers understand and prioritize incoming enquiries, but classification and enforcement are fundamentally different responsibilities.
Consider a simplified classification result:
interface SubmissionAnalysis { category: string; priority: string; summary: string; } An AI classifier might return:
const analysis = { category: "Likely Spam", priority: "Low", summary: "Suspicious promotional content containing a link." }; That tells the application something about the submission. It doesn't necessarily tell the application what to do with it.
If the submission has already been stored as a normal lead and the notification pipeline is allowed to continue, assigning a spam category doesn't prevent anything.
The distinction becomes clearer when you separate classification metadata from enforcement state:
interface Submission { id: string; data: Record<string, unknown>; aiCategory?: string; aiPriority?: string; isSpam: boolean; spamReason?: string; } The AI category describes the submission.
The isSpam property determines whether the submission should participate in the normal processing pipeline.
A submission can therefore have the following state:
{ aiCategory: "Likely Spam", isSpam: false } From the application's perspective, this is still an active submission.
It can appear in the lead pipeline, trigger notifications, and synchronize with external services.
This separation isn't inherently a design mistake. There are good reasons not to let an AI classifier make enforcement decisions automatically.
The important thing is that the application needs an explicit mechanism for deciding when a submission should be quarantined.
A classification is information. Enforcement is a decision.
Confusing the two can leave a system appearing to protect its users while allowing the unwanted behavior to continue.
The production configuration problem
Before introducing new spam detection rules, I investigated the existing submission pipeline.
I traced the request from the public endpoint through the controller, submission service, spam detection logic, database persistence, and notification processing.
The existing implementation already had a rule-based spam detector. It ran before the submission was stored and before downstream operations were triggered.
There was also an existing quarantine mechanism.
So why were suspicious submissions still reaching customers?
The investigation revealed an important configuration detail: the production environment had spam detection running in dry-run mode.
The enforcement logic was effectively equivalent to this:
const spamResult = runSpamChecks(payload); const isDryRun = process.env.SPAM_DRY_RUN === "true"; const enforceSpamBlock = spamResult.isSpam && !isDryRun; When dry-run mode is enabled, the application can detect a suspicious submission without enforcing the result.
The detector might return:
{ isSpam: true, reason: "url_in_content" } But the submission is still persisted as a normal submission because enforcement is disabled.
This is intentional behavior for a dry-run mechanism. It allows developers to observe what a new security rule would do without immediately affecting users.
The problem is that a detection mechanism running in observation mode isn't providing active protection.
I reproduced the suspicious submission patterns locally and confirmed that the existing detector recognized them. The production configuration explained how detected spam could still reach the normal processing pipeline, although I didn't independently reconstruct the complete deployment history of every affected submission.
This was an important reminder that debugging a production system requires more than reading its source code.
The behavior of an application is determined by its code, configuration, infrastructure, and execution environment together.
A function can be completely correct in isolation while the system containing it behaves differently from what you expect.
Why I didn't want AI to make the final decision
Since Formgrid.dev already had AI-powered submission classification, an obvious solution would have been to automatically quarantine everything classified as likely spam.
That would have been relatively straightforward to implement.
But I wasn't comfortable making AI the final authority over whether a customer's enquiry should reach them.
There are several reasons for this.
False positives have real consequences
A message that looks promotional might be a legitimate partnership enquiry.
A message containing financial terminology might be intended for an accounting firm.
A message containing several URLs might be a developer sharing technical documentation or a prospective customer providing examples of websites they like.
An AI model might interpret these patterns differently depending on the surrounding context.
For an application handling business enquiries, incorrectly filtering a genuine message can be more damaging than allowing an occasional unwanted submission through.
Developers need to test their forms
Formgrid.dev is a developer tool.
Developers regularly submit arbitrary content while integrating a form with their applications.
A test submission might look like this:
{ "name": "Test User", "email": "developer@example.com", "message": "Testing form submission" } Others might submit short messages, unusual field values, placeholder content, or links.
These submissions are intentional.
If a developer submits a test form and receives no notification because an AI model silently classified it as spam, the developer might assume that the integration is broken.
A spam protection mechanism should account for how developers actually use the product.
AI introduces additional operational dependencies
An AI-powered enforcement mechanism can introduce inference costs, external service dependencies, latency, and additional failure modes.
If the classification provider is unavailable, the application needs to decide whether to accept the submission, reject it, or wait for classification.
That decision becomes part of the availability model of the submission endpoint.
For obvious spam patterns, I didn't need that complexity.
A deterministic rule can identify certain suspicious combinations locally without making an external API request.
I decided to retain AI as a classification and prioritization mechanism while using rule-based detection for high-confidence spam enforcement.
This isn't an argument that AI is unsuitable for spam detection. It's about assigning responsibilities to the mechanisms best suited to them.
AI is useful for interpreting ambiguous content. Deterministic rules are useful when a decision needs to be predictable, inexpensive, explainable, and easy to test.
Why CAPTCHA alone isn't the answer
CAPTCHA is often the first thing developers think of when discussing form spam.
It can be effective, particularly when combined with server-side verification. But a form backend has different constraints from a single application that controls its entire frontend.
Formgrid.dev supports hosted forms, embedded forms, and custom HTML forms.
Developers can build their own interfaces and submit data directly to the backend using JavaScript or ordinary HTTP requests.
The application cannot assume that every submission originated from a frontend it controls.
For example:
await fetch(formEndpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(formData) }); Any public endpoint that accepts this request must assume that automated clients can also send requests to it.
Client-side validation alone cannot establish whether a request is legitimate.
CAPTCHA, honeypots, rate limiting, and content analysis each address different aspects of the problem.
Honeypots
A honeypot is a hidden field that legitimate visitors are not expected to populate.
<input type="text" name="company_website_confirmation" tabindex="-1" autocomplete="off" hidden /> The backend can treat a populated honeypot as a suspicious signal.
This is inexpensive and doesn't interrupt legitimate visitors, but sophisticated bots can omit the field entirely.
Rate limiting
Rate limiting controls how frequently a client can submit requests.
const allowed = await rateLimiter.consume(clientKey); if (!allowed) { return res.status(429).json({ error: "Too many requests" }); } This helps prevent high-frequency abuse.
However, rate limiting doesn't necessarily tell you whether an individual submission contains spam. A bot submitting one suspicious message every few minutes might remain within the permitted request rate.
CAPTCHA
CAPTCHA introduces an additional verification step to establish whether a request is likely to originate from a legitimate visitor.
It can reduce automated submissions, but making it mandatory introduces integration requirements and potentially additional friction for users.
Content analysis
Content analysis examines what was actually submitted.
It can detect suspicious URLs, promotional scam patterns, malformed values, and other combinations that are inconsistent with the expected purpose of a form field.
None of these mechanisms is a complete solution on its own.
The better approach is layered protection, where different mechanisms address different abuse patterns.
For the problem I was investigating, improving server-side content analysis was the most direct way to address the suspicious submissions without introducing new frontend requirements.
The problem with blocking every URL
The existing spam detector had a relatively broad URL detection rule.
The idea was understandable. Many automated spam submissions contain links directing recipients to suspicious websites.
However, treating the presence of a URL as sufficient evidence of spam creates a serious problem.
Consider this legitimate enquiry:
{ "name": "Daniel", "email": "daniel@example.com", "message": "I'd like a website similar to https://example.com." } Or a form designed to collect website information:
{ "name": "Sarah", "website": "https://example.com", "message": "I'm interested in your services." } Both contain URLs. Neither is inherently spam.
Now compare those with a submission where a financial reward claim and an external link appear in the first-name field.
{ "firstName": "Claim your $3000 reward at https://example.com/reward", "lastName": "x7k2p9", "email": "visitor@example.com" } The URL isn't the only suspicious part of this submission.
It's the combination of the URL, promotional language, and the fact that the content appears in a field intended to contain a person's name.
The meaning of a value depends on the context in which it appears.
A URL in a website field is expected.
A URL in a message field can be legitimate.
A URL accompanied by a financial reward claim in a first-name field is much more suspicious.
The detector needed to understand the role of each field rather than treating every submitted value identically.
Building a field-aware spam detection engine
One of the challenges of building a general-purpose form backend is that you don't control the shape of every incoming payload.
One developer might use:
{ "firstName": "Daniel", "email": "daniel@example.com", "message": "Hello" } Another might use:
{ "customer_name": "Daniel", "contact_email": "daniel@example.com", "project_description": "Hello" } A third might use dynamically generated field identifiers:
{ "field_abc123": "Daniel", "field_def456": "daniel@example.com", "field_ghi789": "Hello" } A detector that assumes every form contains fields called name, email, and message won't work reliably across all these integrations.
Fortunately, forms created using the Formgrid.dev visual form builder already have field metadata.
The backend can use the form's schema to understand whether a submitted value belongs to a name field, email field, website field, textarea, or another input type.
Custom HTML forms may not have the same structured metadata, so the detector also needs a fallback based on recognizable field names.
Conceptually, I divided fields into five roles:
type FieldRole = | "name" | "email" | "website" | "message" | "other"; The detector can then classify each field before evaluating its content.
Here's a simplified example of that approach:
interface FieldMetadata { type?: string; label?: string; } function classifyField( key: string, metadata?: FieldMetadata ): FieldRole { const type = metadata?.type?.toLowerCase(); const normalizedKey = key .toLowerCase() .replace(/[^a-z0-9]/g, ""); if ( type === "url" || type === "website" || type === "link" ) { return "website"; } if (type === "email") { return "email"; } if (type === "textarea") { return "message"; } if ( /^(name|fullname|firstname|lastname|customername)$/ .test(normalizedKey) ) { return "name"; } if ( /^(website|url|homepage|websiteurl)$/ .test(normalizedKey) ) { return "website"; } if ( /^(email|emailaddress|contactemail)$/ .test(normalizedKey) ) { return "email"; } if ( /^(message|description|comments|enquiry|inquiry)$/ .test(normalizedKey) ) { return "message"; } return "other"; } The production implementation is more comprehensive, but the principle is the same: use available schema metadata first, then fall back to field-name heuristics when necessary.
Unknown fields should be handled conservatively.
The absence of metadata shouldn't automatically make a submission suspicious.
This approach allows the spam detector to apply different rules depending on what a field is intended to contain, while maintaining compatibility with existing form integrations.
Normalizing input before evaluating it
A spam detector shouldn't assume that suspicious content will arrive in a consistent format.
URLs and promotional messages can appear in encoded, obfuscated, or visually altered forms.
A detector that only checks for the literal string https:// will miss other representations of the same content.
For example, URLs may appear without a scheme, with encoded characters, or with altered protocol spelling.
This is why normalization is an important part of processing untrusted input.
The general objective is to convert different representations of the same content into a more consistent representation before applying detection rules.
A simplified normalization function might look like this:
function normalizeInput(value: string): string { return value .normalize("NFKC") .replace(/[\u200B-\u200D\uFEFF]/g, "") .trim(); } Unicode normalization helps standardize certain visually equivalent character representations.
Removing zero-width characters prevents invisible characters from interfering with straightforward pattern matching.
Depending on the application, normalization can also include HTML entity decoding and safe handling of percent-encoded input.
However, there's an important distinction between normalizing a value for analysis and modifying the original submission.
I want the detector to evaluate a normalized representation of the content, but I don't want the normalization process to silently change what the customer submitted.
const originalValue = submittedValue; const normalizedValue = normalizeInput(originalValue); const result = evaluateSpamSignals(normalizedValue); The original value can still be preserved for storage and review.
This separation is useful beyond spam detection. Search engines, moderation systems, duplicate detection mechanisms, and input validation pipelines often benefit from distinguishing raw data from its normalized analytical representation.
Normalization is also not a substitute for output escaping, input validation, or other application security controls. Those responsibilities still need to be handled independently.
Using compound signals instead of individual keywords
Another mistake that's easy to make when implementing a spam detector is assuming that certain words are inherently suspicious.
Consider the following words:
- Balance
- Payment
- Account
- Reward
- Sign in
- Credit
These words frequently appear in spam messages, but they also appear in legitimate business communication.
A financial services company might receive enquiries containing all of them.
Blocking submissions simply because they contain financial terminology would be a poor design.
Instead, I wanted the detector to consider combinations of signals.
A promotional financial claim combined with an external link is more informative than either signal independently.
Here's an illustrative implementation:
function containsPromotionalScamLink( value: string ): boolean { const normalized = normalizeInput(value); const hasUrl = containsUrlLikeValue(normalized); const hasRewardClaim = /\b(claim|reward|credited|is waiting)\b/i .test(normalized); const hasFinancialAmount = /[$€£]\s?\d[\d,.]*/.test(normalized); const hasAccountPrompt = /\b(sign in|log in|verify your account)\b/i .test(normalized); return ( hasUrl && hasRewardClaim && (hasFinancialAmount || hasAccountPrompt) ); } This is a simplified example rather than the exact production rule, but it demonstrates the principle.
The presence of a URL alone is insufficient.
The presence of a financial amount alone is insufficient.
The presence of certain promotional claims alongside other suspicious characteristics provides stronger evidence.
This is known as compound-signal detection.
It allows the system to make decisions based on relationships between characteristics rather than treating every individual characteristic as conclusive.
The exact combination of signals matters, and even compound rules can produce false positives. That's why each rule needs regression coverage and production observation before being trusted with automatic enforcement.
Why I moved away from domain-only blocking
During the implementation, I initially considered treating links from certain frequently abused services as suspicious.
The problem is that a service can be used by both legitimate users and spammers.
Telegram, for example, can be used for community invitations, customer support, project coordination, and legitimate business communication.
A publishing platform can host both useful technical documentation and fraudulent promotional content.
A URL redirection service can be used to share ordinary links.
The fact that a service appears in a spam submission doesn't mean every submission containing a link from that service is spam.
I revised the detector so that a recognized domain alone would not automatically cause quarantine when it appeared in an ordinary message field.
The domain could contribute context, but the enforcement decision needed stronger evidence.
This is particularly important for a general-purpose developer tool because the platform serves customers across different industries.
A domain that looks unusual in one business context might be entirely normal in another.
Hard-coded domain restrictions can appear effective against the incidents that inspired them while quietly rejecting legitimate traffic elsewhere.
Designing the submission pipeline
The location of spam detection within the application architecture is just as important as the detection algorithm itself.
Consider a simplified submission pipeline:
Incoming HTTP request | v Validate submission | v Save submission | v Send email notification | v Trigger integrations | v Analyze content If spam detection happens after the application has already sent notifications and triggered integrations, the unwanted side effects have already occurred.
The application might subsequently identify the submission as spam, but it cannot undo an email that has already been delivered.
Moving detection earlier in the pipeline changes what the system can prevent.
Incoming HTTP request | v Validate and normalize input | v Evaluate spam signals | v Is enforcement required? | +---------------------------+ | | Yes No | | v v Save as quarantined Save as normal | | v v Stop downstream Continue normal processing processing | | v v Spam folder Leads, notifications, AI and integrations The spam decision becomes a gate that determines whether the submission is eligible for normal processing.
Here's a simplified TypeScript representation:
async function submitToForm( form: Form, payload: Record<string, unknown> ) { const spamResult = runSpamChecks( payload, form.fieldMetadata ); const dryRun = process.env.SPAM_DRY_RUN === "true"; const shouldQuarantine = spamResult.isSpam && !dryRun; const submission = await submissionRepository.create({ formId: form.id, data: payload, isSpam: shouldQuarantine, spamReason: shouldQuarantine ? spamResult.reason : null }); if (shouldQuarantine) { return submission; } await enqueueSubmissionProcessing(submission.id); return submission; } The important part isn't the specific repository implementation or background job mechanism.
It's the control flow.
A quarantined submission is persisted, but it does not proceed into the normal notification and integration pipeline.
That prevents unnecessary downstream work instead of merely labeling the result after the work has already happened.
The existing Formgrid.dev submission pipeline already had much of this structure. My work focused on improving the detection rules, verifying that the enforcement gate behaved correctly, and testing the operations that should be suppressed.
Quarantine instead of permanent deletion
When an application detects spam, it has several possible responses.
It can reject the request, discard the submission, accept it normally, or store it in a separate quarantine state.
For Formgrid.dev, I preferred quarantine.
A quarantined submission is stored with an explicit state:
{ isSpam: true, spamReason: "promo_scam_link" } The submission remains available for review, but it doesn't appear in the customer's normal lead pipeline.
The normal Leads query can exclude spam:
const leads = await prisma.submission.findMany({ where: { formId, isSpam: false } }); The Spam fold...
