DEV Community

Cover image for SPF PermError and the 10-lookup limit: a 30-line Python script to count yours
MailValid.io
MailValid.io

Posted on AI-assisted

SPF PermError and the 10-lookup limit: a 30-line Python script to count yours

Every SaaS tool that sends email as your domain asks you to add one line to your SPF record: include: its servers. CRM, help desk, newsletter platform, billing. Nobody removes the old ones. One day the record quietly stops working.

The reason is a limit in RFC 7208: evaluating SPF may cost at most 10 DNS lookups. Go over and the result is a permerror, which receivers treat as an SPF failure. Your record still looks fine in your DNS panel.

How common is this?

In October I scanned SPF and DMARC records on 15,000 domains from the Tranco top-sites list (full write-up). Among domains that receive mail and publish SPF:

  • 293 domains (3.0%) were over 10 lookups. The highest count was 49.
  • 95 domains had two SPF records, which is also a permanent error. A domain must have exactly one.

These are popular domains with people looking after them. Disclosure: I work at MailValid, which makes email verification and the free DNS tools linked below.

What counts as a lookup

Not every term costs one. Per RFC 7208, these do:

Term Costs a lookup
include: Yes, plus everything inside the included record
a, mx, ptr, exists: Yes
redirect= Yes, plus everything inside the target
ip4:, ip6:, all No

The catch is the nesting. include:_spf.google.com is one lookup for you, but Google's record includes more records, and every one of those counts against your 10.

Count it yourself

This walks the include tree the same way, using dnspython:

import sys
import dns.resolver


def spf_record(domain):
    answers = dns.resolver.resolve(domain, "TXT")
    txts = [b"".join(r.strings).decode() for r in answers]
    spf = [t for t in txts if t.lower() == "v=spf1" or t.lower().startswith("v=spf1 ")]
    if len(spf) != 1:
        raise ValueError(f"{domain} has {len(spf)} SPF records (needs exactly 1)")
    return spf[0]


def count(domain, depth=0):
    total = 0
    for term in spf_record(domain).split()[1:]:
        t = term.lower().lstrip("+-~?")
        if t.startswith(("include:", "redirect=")):
            target = t.split(":", 1)[1] if t.startswith("include:") else t.split("=", 1)[1]
            print("  " * depth + f"{term}  +1")
            total += 1 + count(target, depth + 1)
        elif t in ("a", "mx", "ptr") or t.startswith(("a:", "a/", "mx:", "mx/", "ptr:", "exists:")):
            print("  " * depth + f"{term}  +1")
            total += 1
    return total


domain = sys.argv[1]
n = count(domain)
print(f"\n{domain}: {n} DNS lookups" + ("  <-- over the limit of 10" if n > 10 else ""))
Enter fullscreen mode Exit fullscreen mode
pip install dnspython
python spfcount.py yourdomain.com
Enter fullscreen mode Exit fullscreen mode

It prints the tree with a +1 next to each term that costs a lookup, so you can see which vendor is eating your budget. When I ran it, it gave 7 for cloudflare.com and 10 for github.com, matching what a full checker reports for both.

It's deliberately small, so it skips a few things a receiver also does: SPF macros, the extra address lookups behind mx, and the separate limit of two "void" lookups that return nothing. If you'd rather not run code, the free SPF record checker follows the whole include tree, counts it against the limit and flags duplicate records.

Getting back under 10

In rough order of effort:

  1. Delete includes for tools you no longer use. This is the most common fix. Check with your team before removing anything; a forgotten tool may still send invoices or password resets.
  2. Replace a and mx with ip4:/ip6: if those servers' addresses are stable. Each swap saves a lookup.
  3. Move a vendor to a subdomain. Bulk mail sent from news.yourdomain.com can have its own SPF record and its own 10-lookup budget.
  4. Flattening (replacing includes with the IP ranges they resolve to) gets you under the limit, but the vendor's ranges change without telling you. Only do it with something that re-flattens automatically.

SPF is only a third of it

Gmail and Yahoo have required bulk senders to publish SPF, DKIM and DMARC since February 2024. A broken SPF record makes DMARC depend entirely on DKIM, so it's worth checking all three together. Our guide to SPF, DKIM and DMARC explains how they fit, and the DKIM checker and DMARC checker cover the other two records.

What's the highest lookup count you've seen on a real domain? I'd like to know if anyone beats 49.

Top comments (1)

Collapse
 
acemeridian profile image
Ace Meridian •

I ran your spfcount.py unchanged (dnspython 2.9.2, Python 3.14) and got your numbers, 10 for github.com and 7 for cloudflare.com, but only after pointing it at 1.1.1.1. Three things came up on the way:

stub 127.0.0.53 : ValueError: github.com has 0 SPF records (needs exactly 1)
1.1.1.1         : github.com: 10 DNS lookups
1.1.1.1         : cloudflare.com: 7 DNS lookups
loop            : RecursionError: maximum recursion depth exceeded
redirect+all    : r.test: 13 DNS lookups  <-- over the limit of 10
void            : NXDOMAIN: The DNS query name does not exist.
Enter fullscreen mode Exit fullscreen mode
  1. The first run used my default resolver (systemd-resolved, forwarding to a home router). It returned 7 of github.com's 24 TXT records with no truncation flag, the SPF one wasn't among them, and the script said the domain has no SPF record. A receiver resolving through a proper resolver would see it fine, so that's a false alarm, and an easy one to believe when the error message is that confident. Giving the script its own dns.resolver.Resolver(configure=False) with explicit nameservers made it match.

  2. v=spf1 ip4:192.0.2.1 redirect=x.test -all counts 13 and gets flagged as over the limit. RFC 7208 section 6.1 says redirect= is ignored when the record has an all mechanism, so a receiver does 0 lookups for that record. I see this "redirect plus -all" combination on real domains when someone adds a provider's redirect without removing their old ending.

  3. A pair of records that include each other ends in a RecursionError instead of a permerror, and one include that points at a deleted vendor domain (NXDOMAIN) crashes the whole walk instead of counting toward the two-void-lookup limit you mention. The loop case gets handled for free if count() stops as soon as the running total goes over 10, since that's where a receiver stops too.

Were your 293 over-limit domains counted with a full evaluator, or with a static walk like this one? The redirect case could move that number slightly in either direction.