DEV Community

seller-mind
seller-mind

Posted on

Rethinking SaaS Architecture: Moving Heavy Lifting to the Edge

A few months ago, I was putting the finishing touches on a new SaaS project. I had the UI looking sharp, the database humming along, and the Stripe billing webhooks firing perfectly. But when I started testing the core feature—a webpage SEO analyzer—things got ugly. My initial tests from my local machine in the US were fine, but when a friend in Berlin tried it, the request took over three seconds just to resolve.

I realized my entire backend was centralized in a single US region. Every time a user submitted a URL, the server had to fetch the target page, parse the HTML, and run checks, all from one geographic location. It was a bottleneck I hadn't anticipated. I needed a way to process these requests closer to the user without rewriting my entire backend or managing a fleet of global servers. So I decided to build something.

The Problem with Centralized Compute

The shift toward global SaaS products has outpaced how many of us architect our backends. We often default to deploying our Node.js or Next.js apps to a single primary region because it's easy and keeps our infrastructure simple. But when your application involves fetching external resources—like scraping a webpage for SEO analysis, processing images, or running heavy regex operations—that centralization becomes a significant liability.

The cost of ignoring this isn't just a slightly slower app. In the SaaS world, perceived performance is just as critical as actual performance. If your tool takes four seconds to return a result because the server is physically 5,000 miles away from the user, they aren't going to blame the speed of light; they're going to blame your app.

The challenge is figuring out how to distribute this compute-heavy logic. You want to keep your core business logic, authentication, and database operations in a centralized, secure environment, but you need the heavy, stateless lifting to happen closer to the user.

A Technical Approach to Edge Computing

The industry trend right now is moving away from monolithic backend servers toward edge computing. Instead of routing all traffic to a central data center, edge computing pushes your code to servers distributed globally, running it as close to the user as possible.

For my SEO analyzer, this meant moving the HTML fetching and parsing logic out of my main Next.js API routes and into Cloudflare Workers. Since I was using a Next.js 14+ App Router setup, I wanted to keep the authentication (via NextAuth) and billing on the main server, while offloading the actual SEO analysis to the edge.

Here is what the edge worker logic looks like:

// Cloudflare Worker for edge SEO analysis
export default {
  async fetch(request, env) {
    const url = new URL(request.url);
    if (url.pathname !== '/api/analyze') {
      return new Response('Not found', { status: 404 });
    }

    const targetUrl = url.searchParams.get('url');
    if (!targetUrl) {
      return new Response(JSON.stringify({ error: 'Missing url' }), {
        status: 400,
        headers: { 'Content-Type': 'application/json' },
      });
    }

    // Fetch target page at the edge (low latency worldwide)
    const response = await fetch(targetUrl, {
      cf: { cacheTtl: 300, cacheEverything: true },
    });
    const html = await response.text();

    // Run SEO checks (regex-based, no DOM needed)
    const title = html.match(/<title[^>]*>([^<]*)<\/title>/i)?.[1] || '';
    const desc = html.match(/<meta[^>]*name=["']description["'][^>]*content=["']([^"']*)["']/i)?.[1] || '';
    const h1Count = (html.match(/<h1[ >]/gi) || []).length;

    return new Response(JSON.stringify({ title, desc, h1Count }), {
      headers: { 'Content-Type': 'application/json' },
    });
  },
};
Enter fullscreen mode Exit fullscreen mode

There are a few key decisions in this architecture. First, notice the cf object in the fetch request. This tells the Cloudflare network to cache the target page's HTML at the edge for 300 seconds. If another user in the same region requests the same URL shortly after, the worker doesn't even need to fetch it from the origin server; it just reads it from the edge cache.

Second, I intentionally avoided using a heavy DOM parsing library. Initially, I tried bringing in a full HTML parser, but it bloated the worker's startup time and memory usage. By switching to regex-based extraction for basic tags like titles, meta descriptions, and H1 counts, I kept the worker highly performant. For a quick SEO check, this is more than enough.

Finally, the Next.js frontend simply makes a standard fetch request to this worker endpoint. Because the worker is deployed globally, the browser resolves the DNS to the nearest edge location, executes the code there, and returns the JSON response in a fraction of the time it would take to route back to a central US server.

Practical Results and Takeaways

Moving the SEO analysis to the edge significantly improved the performance profile of the app. For example, a request that previously took 2.5 seconds for an international user might now resolve in under 400 milliseconds.

What surprised me most was how little code I actually had to write. Cloudflare Workers support modern JavaScript and TypeScript, so I didn't have to learn a new framework; I just adapted my existing logic. The type safety carried over seamlessly from my main Next.js codebase.

One trade-off I had to navigate was the lack of a traditional DOM environment at the edge. As mentioned, I had to rely on regex instead of DOM querying. If I needed to do deep, complex DOM manipulation, I would have had to rethink the approach entirely.

If I were to do this again, I'd probably abstract the edge worker logic and its TypeScript interfaces into a shared monorepo package earlier, rather than duplicating types between the Next.js app and the worker. Keeping the types in sync manually was a bit tedious.

Try It Yourself

If you're curious about how this edge architecture performs in practice, or if you just need to check your own site's basic SEO health, I've extracted this edge logic into a standalone free tool. You can try the SEO Checker at saaslaunch.dev/free-tools/seo-checker. It runs entirely on the edge, so you'll get your results instantly, no matter where you are in the world.


Full disclosure: I'm the developer of SaaSLaunch. I built this because I needed it myself.

Top comments (0)