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 folder can retrieve quarantined submissions:
const spam = await prisma.submission.findMany({
where: {
formId,
isSpam: true
}
});
If a customer discovers that a submission was incorrectly classified, the application can restore it using an authorized operation.
await prisma.submission.updateMany({
where: {
id: submissionId,
formId: authorizedFormId,
isSpam: true
},
data: {
isSpam: false,
spamReason: null
}
});
The authorization requirement matters. A customer should only be able to restore submissions belonging to forms they are permitted to manage.
Quarantine provides several advantages.
First, the customer doesn't permanently lose access to the submitted information.
Second, the engineering team has a way to investigate false positives.
Third, the system can make an enforcement decision without treating that decision as irreversible.
Fourth, the reason associated with the quarantine provides useful context when investigating why a submission was flagged.
There is a trade-off: storing quarantined submissions still consumes database resources.
At larger scales, a system may need retention policies, storage quotas, or other controls to prevent the quarantine itself from becoming a resource exhaustion problem.
But for a form backend where legitimate enquiries can have significant business value, recoverability is an important property.
One additional consideration is that restoring a submission doesn't automatically mean previously suppressed notifications and integrations have been replayed. Those operations require an explicit recovery policy.
Restoring data and replaying side effects are separate responsibilities.
Preventing downstream side effects
A form submission isn't just a database record. It's an event that can cause other parts of the system to perform work.
This means spam protection must be considered in the context of the application's side effects.
In Formgrid.dev, a normal submission can participate in operations such as email notifications, automated responses, AI classification, webhooks, and external integrations.
The enforcement path needs to prevent quarantined submissions from initiating those operations.
An early return in the submission service is a useful first layer of protection.
However, in applications with background workers, asynchronous processing, and deferred operations, checking the submission state only at the original HTTP request boundary may not always be sufficient.
Consider a hypothetical notification worker:
async function processNotificationJob(
submissionId: string
) {
const submission =
await submissionRepository.findById(submissionId);
if (!submission || submission.isSpam) {
return;
}
await notificationService.send(submission);
}
The worker independently checks whether the submission is eligible for processing.
This is an example of defense in depth.
The submission service should avoid scheduling unnecessary work in the first place, while downstream consumers can provide an additional safeguard.
Reloading the submission from the database can also be useful when its state might have changed between job creation and job execution.
That doesn't eliminate every possible concurrency problem. For example, a submission could still be marked as spam after a worker checks its state but before an external email provider accepts the request.
More complex systems may require stronger coordination, explicit job cancellation, or carefully defined processing states.
But the architectural principle remains useful: enforce important business invariants at the boundaries where irreversible side effects occur.
During the review of Formgrid.dev, I also examined deferred file-upload processing and notification jobs to verify that quarantined submissions would not proceed through those paths.
The objective was not merely to hide spam from the dashboard. It was to prevent spam from consuming the resources and external services associated with legitimate submissions.
Why a spam detector should explain its decisions
A detector that returns only a boolean can tell the application whether a submission is suspicious.
function isSpam(payload: unknown): boolean {
// Detection logic
}
But it cannot tell an engineer why the decision was made.
A more useful result includes a reason:
type SpamResult =
| {
isSpam: false;
}
| {
isSpam: true;
reason: string;
};
For example:
{
isSpam: true,
reason: "url_in_content"
}
Or:
{
isSpam: true,
reason: "promo_scam_link"
}
Reason codes make the detector easier to observe, test, and maintain.
If a particular rule starts producing a large number of detections after a deployment, the engineering team can investigate that rule rather than treating the detector as a black box.
They also make it possible to write more precise regression tests.
Instead of simply asserting that a submission was flagged, a test can verify that it was flagged for the expected reason.
expect(result.isSpam).toBe(true);
expect(result.reason).toBe("url_in_content");
That distinction matters because a test can pass for the wrong reason.
A suspicious submission might be detected because of its email address rather than the URL pattern the test was intended to verify.
Checking the reason helps establish that the specific rule under investigation actually works.
Structured reasons are also valuable for observability.
Rather than logging complete submission contents, which may contain sensitive personal information, an application can record detection counts and reason codes.
logger.info("Spam detection", {
reason: result.reason,
mode: dryRun ? "observe" : "enforce"
});
This provides operational visibility while reducing the need to expose customer data in application logs.
The importance of dry-run mode
The production configuration that explained the original behavior was also an important mechanism for deploying the improved detector safely.
Dry-run mode allows the application to evaluate a decision without immediately enforcing it.
const result = runSpamChecks(payload);
if (result.isSpam) {
logger.info("Spam detected", {
reason: result.reason,
mode: dryRun ? "observe" : "enforce"
});
}
const shouldQuarantine =
result.isSpam && !dryRun;
When dry-run mode is enabled, the application can record what it would have classified as spam while allowing the existing processing behavior to continue.
This is useful because test environments cannot reproduce every variation of real production traffic.
A detector can pass every unit test and still behave unexpectedly when customers submit content from industries or use cases that weren't represented in the test dataset.
Dry-run mode gives engineers an opportunity to observe those decisions before allowing them to affect users.
It also separates two operations that are often unnecessarily coupled:
- Deploying new code.
- Activating new behavior.
Deploying an improved spam detector doesn't have to mean immediately quarantining every submission it identifies.
The code can be deployed first, observed, and then activated when there is sufficient confidence in its behavior.
This is a form of shadow evaluation and controlled feature rollout.
The same technique can be applied to fraud detection, pricing rules, authorization policies, recommendation systems, and data migration logic.
Whenever a new decision mechanism could negatively affect users, there is value in evaluating its decisions before making them authoritative.
Testing a spam detector properly
Testing a spam detector involves more than checking whether obvious spam gets detected.
A detector that classifies every submission as spam would achieve perfect detection of spam in a dataset, but it would be completely unusable.
The legitimate submissions are just as important as the suspicious ones.
I approached testing across several layers.
Unit tests for individual detection rules
The first layer verifies the behavior of the detection functions independently.
For example, a suspicious URL in a name field should be detected:
it("detects suspicious URLs in name fields", () => {
const result = runSpamChecks({
firstName:
"Claim your $3000 reward https://example.com/reward",
lastName: "Visitor",
email: "visitor@example.com"
});
expect(result.isSpam).toBe(true);
expect(result.reason).toBe("url_in_content");
});
A legitimate URL in a message field should be accepted:
it("allows legitimate URLs in message fields", () => {
const result = runSpamChecks({
name: "Daniel",
email: "daniel@example.com",
message:
"Please review the documentation at https://example.com/docs"
});
expect(result.isSpam).toBe(false);
});
A website field should accept a URL:
it("allows URLs in website fields", () => {
const result = runSpamChecks({
name: "Sarah",
email: "sarah@example.com",
website: "https://example.com"
});
expect(result.isSpam).toBe(false);
});
These tests establish that the detector understands the difference between suspicious content and expected field values.
Testing legitimate developer submissions
Because the application is a developer tool, normal integration testing needs explicit coverage.
it("allows ordinary test submissions", () => {
const result = runSpamChecks({
name: "Test User",
email: "developer@example.com",
message: "Testing form submission"
});
expect(result.isSpam).toBe(false);
});
This might look like a trivial test, but it protects an important product behavior.
A developer testing an integration should not accidentally encounter a security rule that makes the integration appear broken.
Testing unexpected but legitimate content
The review also exposed some less obvious problems in existing detection rules.
For example, an aggressive arrow-detection rule could classify technical messages containing JavaScript syntax as spam.
const transform = (value) => value.trim();
A developer might legitimately paste something like this into a support enquiry.
Similarly, a Unicode regular expression using the Emoji property can match certain ASCII digits because those digits participate in emoji sequences.
const containsEmoji = /\p{Emoji}/u;
containsEmoji.test("12"); // true
That behavior can be surprising if the intended rule is to detect pictographic emoji.
A more targeted Unicode property is useful for that specific purpose:
const containsPictograph =
/\p{Extended_Pictographic}/u;
This isn't a complete solution for detecting every possible emoji sequence, but it avoids the specific problem of treating ordinary digits as emoji characters.
The implementation review tightened these rules and added coverage for legitimate technical messages, international names, short natural replies, and ordinary links.
These are examples of why input validation deserves careful testing even when the implementation appears straightforward.
A regular expression can be syntactically correct and still be semantically wrong for the product using it.
Regression tests based on actual incidents
The suspicious submissions that motivated the investigation were reproduced locally using representative payloads.
This is one of the most useful habits in debugging production systems.
When you encounter an unexpected production behavior, convert that behavior into a reproducible test before or alongside the fix.
Otherwise, the implementation may solve the immediate problem without protecting against its reintroduction later.
The regression tests covered the original suspicious patterns, including promotional financial claims, URLs in name fields, and obfuscated or schemeless links.
They also covered legitimate content that the previous detector could incorrectly classify.
The objective was to preserve the useful behavior of the existing detector while correcting its overly broad assumptions.
Testing enforcement rather than detection alone
A detector returning isSpam: true doesn't prove that the application actually protects its customers.
The submission pipeline itself needs tests.
A simplified regression test might look like this:
it("quarantines spam without sending notifications", async () => {
process.env.SPAM_DRY_RUN = "false";
const submission = await submissionService.submitToForm(
form,
suspiciousPayload
);
expect(submission.isSpam).toBe(true);
expect(notificationService.send)
.not.toHaveBeenCalled();
expect(webhookService.dispatch)
.not.toHaveBeenCalled();
expect(integrationService.sync)
.not.toHaveBeenCalled();
});
The opposite behavior also needs coverage.
When dry-run mode is enabled, detection should not unexpectedly activate quarantine.
it("observes spam without enforcing in dry-run mode", async () => {
process.env.SPAM_DRY_RUN = "true";
const submission = await submissionService.submitToForm(
form,
suspiciousPayload
);
expect(submission.isSpam).toBe(false);
});
In an actual test suite, environment variables should be restored between tests so that one test's configuration doesn't influence another.
These tests protect the system's behavior, not just the implementation of a particular detection function.
All notification and integration assertions were performed using mocks. There was no need to send real emails or trigger customer integrations to verify the control flow.
Evaluating false positives and false negatives
There are four possible outcomes when a spam detector evaluates a submission.
| Actual submission | Detector decision | Outcome |
|---|---|---|
| Spam | Spam | True positive |
| Legitimate | Legitimate | True negative |
| Legitimate | Spam | False positive |
| Spam | Legitimate | False negative |
A false positive occurs when a legitimate submission is incorrectly classified as spam.
A false negative occurs when an actual spam submission passes through the detector.
Both matter, but their relative cost depends on the application.
For a form backend used to collect business enquiries, false positives deserve particular attention.
A missed spam message is inconvenient.
A missed customer enquiry can represent lost revenue.
Two useful metrics for evaluating detection systems are precision and recall.
Precision = True positives /
(True positives + False positives)
Recall = True positives /
(True positives + False negatives)
Precision answers the question: of all submissions classified as spam, how many were actually spam?
Recall answers a different question: of all actual spam submissions, how many did the detector identify?
A more aggressive detector may improve recall while reducing precision.
A more conservative detector may improve precision while allowing additional spam to pass through.
The right balance depends on the cost of each type of error.
As part of the validation process, I created a synthetic evaluation corpus containing both legitimate and suspicious submissions.
The final local results were:
| Metric | Result |
|---|---|
| Synthetic evaluation cases | 18 |
| Legitimate submissions | 11 |
| Spam submissions | 7 |
| False positives | 0 |
| False negatives | 0 |
| Relevant automated tests passed | 61 |
| TypeScript type checking | Passed |
The results were encouraging, but it's important to understand what they mean.
Eighteen synthetic cases are not sufficient to establish a production accuracy rate.
The detector performed correctly on the cases represented in that dataset. That doesn't mean it will perform perfectly across every possible submission.
Historical production submissions were not evaluated during this implementation stage.
The actual production false-positive and false-negative rates therefore remain unverified.
This distinction matters because engineering confidence should come from evidence, not from extending limited test results into claims they cannot support.
Why alternative entry points matter
One of the more useful findings from reviewing the application was that not every submission necessarily enters the system through the same service.
The main public submission flow handles ordinary hosted, embedded, and custom HTML forms.
However, applications evolve.
A form backend might later introduce authenticated API imports, payment confirmation flows, administrative operations, or other mechanisms that create submission records.
Each additional entry point creates a question: does it enforce the same business rules as the main submission pipeline?
Consider the following architecture:
Public form endpoint
|
v
Submission service
|
v
Spam checks
|
v
Database
Now imagine introducing another entry point:
Payment confirmation
|
v
Database
Or an authenticated API import:
Public API
|
v
Database
The main submission service may have excellent spam protection, but that doesn't automatically mean every other path has the same guarantees.
During the review, I identified alternative submission paths that did not use the same heuristic spam checks.
I documented them as follow-up work rather than silently expanding the scope of the existing implementation.
That was a deliberate decision.
An authenticated import operation may have different requirements from an anonymous public form submission.
A payment confirmation flow may need to preserve transaction-related information even when associated form content appears suspicious.
Applying the same rules indiscriminately could introduce unintended behavior.
The longer-term architectural question is whether the application should centralize submission eligibility policies while allowing different entry points to apply explicitly defined rules.
This is a common problem in growing backend applications.
Business invariants that initially exist in one service can become inconsistent as new controllers, workers, and integration paths are introduced.
Reviewing every entry point is often more valuable than adding another validation rule to the most obvious one.
Rate limiting and distributed systems
Although content detection was the main focus of this investigation, rate limiting remains an important part of protecting public APIs.
A simple rate limiter can be implemented using an in-memory map.
const requests = new Map<string, number>();
For a single running process, this can be sufficient for basic request tracking.
But if the application scales horizontally across multiple backend instances, each process maintains its own independent map.
Incoming requests
|
v
Load balancer
|
+---------------------------+
| |
v v
Backend instance A Backend instance B
Local request counter Local request counter
A client might send requests to both instances without either individual instance observing the complete request volume.
The effective rate limit becomes dependent on how requests are distributed.
This is where shared infrastructure such as Redis becomes useful.
Incoming requests
|
v
Load balancer
|
+---------------------------+
| |
v v
Backend instance A Backend instance B
| |
+-------------+-------------+
|
v
Shared Redis state
Both backend instances can consult a shared rate-limiting state.
A simplified Redis-based fixed-window limiter might look like this:
async function consumeRateLimit(
redis: Redis,
key: string,
limit: number,
windowSeconds: number
) {
const result = await redis.eval(
`
local count = redis.call("INCR", KEYS[1])
if count == 1 then
redis.call("EXPIRE", KEYS[1], ARGV[1])
end
return count
`,
1,
key,
windowSeconds
);
return Number(result) <= limit;
}
The increment and expiration logic are executed together atomically.
This avoids a failure mode where a counter is incremented but its expiration is never established because the application fails between two separate Redis commands.
A fixed-window limiter still has limitations, including bursts around window boundaries. More demanding systems might use sliding-window algorithms or token buckets.
There are also additional considerations around trusted proxy configuration, shared IP addresses, per-form quotas, and what happens when Redis is unavailable.
I didn't introduce a distributed rate-limiting rewrite as part of this spam protection implementation. It's a separate infrastructure improvement worth considering as the platform scales.
The broader lesson is that abuse prevention mechanisms need to match the application's deployment architecture.
A mechanism that works correctly inside one process may not provide the same guarantees across several processes.
A controlled production rollout
After completing the implementation and local validation, the next decision was whether to immediately enable enforcement in production.
The tempting approach would be to deploy the code and switch the spam protection setting at the same time.
But a security feature that can suppress legitimate customer enquiries deserves a more controlled release process.
The rollout plan separates deployment from enforcement:
- Deploy the improved spam detection code while keeping dry-run mode enabled.
- Verify that production is running the intended release.
- Observe detection reasons and volumes against real submission traffic.
- Investigate suspicious patterns and potential false positives.
- Enable quarantine enforcement once the results justify doing so.
- Verify that quarantined submissions appear in the Spam folder rather than the normal lead pipeline.
- Confirm that notifications and integrations are suppressed for quarantined submissions.
- Continue monitoring and restore incorrectly classified submissions when necessary.
The rollback mechanism is equally important.
If the new rules behave unexpectedly, enforcement can be disabled by returning the application to dry-run mode and restarting or redeploying the service as required.
The detection logic can continue to run without automatically quarantining submissions.
Previously quarantined records still need to be reviewed and restored separately.
That is another reason I preferred quarantine over deletion.
At the time of writing, the implementation and local validation are complete, but the controlled production enforcement rollout is still pending.
I haven't claimed that the new detector has eliminated production spam or measured its production accuracy because those conclusions require evidence from the actual deployment.
A successful test suite establishes confidence in the scenarios it covers. Production observation establishes confidence in how the system behaves under real conditions.
Both are necessary.
What this taught me about backend engineering
This investigation started with suspicious messages appearing in customers' lead pipelines.
It turned into a review of input normalization, field metadata, deterministic detection, asynchronous processing, production configuration, data recoverability, testing, and release engineering.
Several lessons stood out.
Detection and enforcement are different responsibilities.
Identifying an unwanted event doesn't prevent it from producing side effects. The application needs an explicit decision about whether that event should continue through the system.
Context matters more than isolated patterns.
A URL, a financial term, or a short message is not inherently spam. Understanding the purpose of the field and the relationship between signals produces more meaningful decisions.
Protecting legitimate users is part of security engineering.
A security mechanism that regularly prevents legitimate users from completing their intended actions is not necessarily successful.
The placement of a check matters as much as the check itself.
Detecting spam before triggering external services can prevent unnecessary processing. Detecting it afterward can only describe what has already happened.
Recoverability is an architectural property.
Quarantining data instead of deleting it makes incorrect decisions easier to investigate and recover from.
Production configuration is part of the system.
The behavior of an application cannot be understood from its source code alone. Environment variables, feature flags, deployment versions, and infrastructure configuration can fundamentally change what the code does.
Tests need to verify business behavior.
A passing detection test doesn't establish that emails, webhooks, and integrations are suppressed. Those outcomes require their own assertions.
Deployment and activation don't have to happen together.
Dry-run modes and feature flags allow engineers to introduce new decision mechanisms without immediately exposing customers to their consequences.
These principles extend far beyond spam protection.
They apply to fraud detection, payment processing, authorization systems, notification platforms, content moderation, and almost any backend system where an incoming event can trigger downstream operations.
Closing
The most interesting part of building Formgrid.dev hasn't always been implementing new features.
Sometimes it's investigating why an existing feature isn't producing the outcome I expected.
In this case, the solution wasn't to introduce a more powerful AI model, add another external service, or rewrite the entire submission system.
It was to understand the existing architecture, identify where detection and enforcement differed, improve the quality of the rules, verify the downstream behavior, and establish a safer deployment process.
That's one of the things I find particularly interesting about backend engineering.
The challenge is rarely just making a function return the correct value. It's making sure that the entire system behaves correctly when that value influences other operations.
For a SaaS product, those operations ultimately affect real people and real businesses.
Every unnecessary notification consumes someone's attention. Every unnecessary integration request consumes resources. Every legitimate enquiry incorrectly filtered could represent a lost business opportunity.
Good engineering requires understanding those consequences before deciding how the system should behave.
If you're building a public-facing API, a form backend, or any application that accepts untrusted user input, I would encourage you to look beyond the detection algorithm itself.
Ask where the decision is enforced, what side effects it prevents, how incorrect decisions can be recovered from, and how you can safely introduce changes without disrupting the people who depend on your application.
Those questions are often more important than the particular regular expression, AI model, or security library you choose.
If you've encountered similar challenges while building spam protection or abuse prevention systems, I'd genuinely like to hear how you approached them. Reach me at allen@formgrid.dev.
I'm Allen, a full-stack software engineer and the founder of Formgrid.dev, an open-source form backend, form builder, website builder, and lead management platform, and Sheetrocket. This tool turns Google Sheets into REST APIs and embeddable widgets. I write about backend engineering, system design, infrastructure, and the lessons I learn from building real software products. More at jonesstack.com.
Top comments (0)