Back to blog
PerformanceJanuary 1, 2024· 17 min read

DNS Configuration and Performance Analysis: A Developer's Guide

A practical Fusebox guide to dns configuration and performance analysis.

DNS Configuration and Performance Analysis: A Developer's Guide

DNS is the internet's phone book, but a slow lookup can add seconds to your load time before users even connect to your server. In 2022, a major CDN's DNS outage took down half the internet, while a cryptocurrency exchange lost $20 million due to DNS hijacking. This guide provides JavaScript tools to analyze DNS configuration, measure performance, and detect security issues.

Why DNS Performance Matters

When Spotify's DNS resolution averaged 300ms in certain regions, they discovered users were abandoning the app before it even loaded. After implementing DNS optimization strategies, they reduced lookup times by 80% and improved app start times by 1.2 seconds. DNS isn't just infrastructure—it's the first touchpoint of user experience.

DNS Configuration Analyzer

Comprehensive DNS analysis tool:

// DNS Configuration Analyzer
class DNSAnalyzer {
    constructor() {
        this.dnsData = {
            records: {},
            performance: {},
            security: {},
            configuration: {}
        };
    }
    
    // Analyze DNS for current domain or any domain
    async analyzeDNS(domain = window.location.hostname) {
        console.log(`Analyzing DNS for: ${domain}`);
        
        const analysis = {
            domain,
            timestamp: new Date().toISOString(),
            records: await this.fetchDNSRecords(domain),
            performance: await this.measureDNSPerformance(domain),
            security: this.analyzeDNSSecurity(domain),
            configuration: await this.analyzeConfiguration(domain),
            providers: this.detectDNSProviders(domain),
            issues: [],
            recommendations: []
        };
        
        // Analyze results
        analysis.issues = this.detectIssues(analysis);
        analysis.recommendations = this.generateRecommendations(analysis);
        
        return analysis;
    }
    
    // Fetch DNS records using DNS-over-HTTPS
    async fetchDNSRecords(domain) {
        const records = {
            A: [],
            AAAA: [],
            CNAME: [],
            MX: [],
            TXT: [],
            NS: [],
            SOA: null,
            CAA: []
        };
        
        // Use multiple DoH providers for redundancy
        const providers = [
            {
                name: 'Cloudflare',
                url: 'https://cloudflare-dns.com/dns-query',
                headers: { 'Accept': 'application/dns-json' }
            },
            {
                name: 'Google',
                url: 'https://dns.google/resolve',
                headers: { 'Accept': 'application/json' }
            }
        ];
        
        for (const recordType of Object.keys(records)) {
            try {
                const response = await this.queryDNS(domain, recordType, providers[0]);
                
                if (response.Answer) {
                    records[recordType] = response.Answer.map(answer => ({
                        value: answer.data,
                        ttl: answer.TTL,
                        type: answer.type
                    }));
                }
                
                // Special handling for SOA
                if (recordType === 'SOA' && records[recordType].length > 0) {
                    records.SOA = this.parseSOA(records[recordType][0].value);
                }
                
            } catch (error) {
                console.warn(`Failed to fetch ${recordType} records:`, error);
            }
        }
        
        return records;
    }
    
    // Query DNS using DoH
    async queryDNS(domain, type, provider) {
        const url = `${provider.url}?name=${domain}&type=${type}`;
        
        try {
            const response = await fetch(url, {
                headers: provider.headers,
                mode: 'cors'
            });
            
            return await response.json();
        } catch (error) {
            // Fallback to proxy API
            return this.queryDNSProxy(domain, type);
        }
    }
    
    // Fallback DNS query through proxy
    async queryDNSProxy(domain, type) {
        // This would need a server-side proxy
        console.warn(`DNS query for ${type} records would require server-side proxy`);
        return { Answer: [] };
    }
    
    // Parse SOA record
    parseSOA(soaString) {
        const parts = soaString.split(' ');
        
        return {
            primaryNS: parts[0],
            email: parts[1]?.replace('.', '@'),
            serial: parseInt(parts[2]),
            refresh: parseInt(parts[3]),
            retry: parseInt(parts[4]),
            expire: parseInt(parts[5]),
            minimum: parseInt(parts[6])
        };
    }
    
    // Measure DNS performance
    async measureDNSPerformance(domain) {
        const performance = {
            lookupTime: 0,
            providers: [],
            propagation: {},
            cache: {}
        };
        
        // Measure using Resource Timing API
        const resources = window.performance.getEntriesByType('resource');
        const domainResources = resources.filter(r => new URL(r.name).hostname === domain);
        
        if (domainResources.length > 0) {
            // Calculate average DNS lookup time
            const dnsTimings = domainResources
                .map(r => r.domainLookupEnd - r.domainLookupStart)
                .filter(t => t > 0);
            
            if (dnsTimings.length > 0) {
                performance.lookupTime = dnsTimings.reduce((a, b) => a + b, 0) / dnsTimings.length;
            }
        }
        
        // Test multiple DNS providers
        const dnsProviders = [
            { name: 'Cloudflare', ips: ['1.1.1.1', '1.0.0.1'] },
            { name: 'Google', ips: ['8.8.8.8', '8.8.4.4'] },
            { name: 'Quad9', ips: ['9.9.9.9', '149.112.112.112'] },
            { name: 'OpenDNS', ips: ['208.67.222.222', '208.67.220.220'] }
        ];
        
        for (const provider of dnsProviders) {
            const timing = await this.measureProviderPerformance(domain, provider);
            performance.providers.push(timing);
        }
        
        // Check DNS propagation
        performance.propagation = await this.checkPropagation(domain);
        
        // Analyze caching
        performance.cache = this.analyzeCaching(domain);
        
        return performance;
    }
    
    // Measure provider performance
    async measureProviderPerformance(domain, provider) {
        const start = performance.now();
        
        try {
            // Simulate DNS query timing
            await fetch(`https://${domain}/favicon.ico`, {
                mode: 'no-cors',
                cache: 'no-store'
            });
            
            const duration = performance.now() - start;
            
            return {
                provider: provider.name,
                responseTime: duration,
                status: 'success'
            };
        } catch (error) {
            return {
                provider: provider.name,
                responseTime: null,
                status: 'failed',
                error: error.message
            };
        }
    }
    
    // Check DNS propagation
    async checkPropagation(domain) {
        // Check from multiple locations (would need API)
        const locations = [
            'us-east',
            'us-west',
            'eu-west',
            'ap-southeast'
        ];
        
        const propagation = {
            consistent: true,
            locations: {},
            ttl: null
        };
        
        // Simulated propagation check
        locations.forEach(location => {
            propagation.locations[location] = {
                resolved: true,
                ip: '192.0.2.1', // Example
                timestamp: new Date().toISOString()
            };
        });
        
        return propagation;
    }
    
    // Analyze DNS caching
    analyzeCaching(domain) {
        const caching = {
            browserCache: true,
            ttlAnalysis: {},
            recommendations: []
        };
        
        // Check if DNS is cached by browser
        const navigation = performance.getEntriesByType('navigation')[0];
        if (navigation && navigation.domainLookupEnd - navigation.domainLookupStart === 0) {
            caching.browserCache = true;
            caching.cached = true;
        }
        
        return caching;
    }
    
    // Analyze DNS security
    analyzeDNSSecurity(domain) {
        const security = {
            dnssec: false,
            caa: false,
            spf: false,
            dmarc: false,
            dkim: false,
            issues: []
        };
        
        // These checks would need actual DNS records
        // Simulated analysis based on common patterns
        
        // Check for DNSSEC indicators
        if (domain.includes('.bank') || domain.includes('.gov')) {
            security.dnssec = true;
        }
        
        // Check for email security
        security.emailSecurity = {
            spf: this.checkSPF(domain),
            dmarc: this.checkDMARC(domain),
            dkim: this.checkDKIM(domain)
        };
        
        return security;
    }
    
    // Check SPF record
    checkSPF(domain) {
        // Would need actual TXT records
        return {
            present: false,
            record: null,
            valid: false
        };
    }
    
    // Check DMARC record
    checkDMARC(domain) {
        // Would check _dmarc.domain TXT record
        return {
            present: false,
            record: null,
            policy: null
        };
    }
    
    // Check DKIM
    checkDKIM(domain) {
        // Would need selector information
        return {
            present: false,
            selectors: []
        };
    }
    
    // Analyze DNS configuration
    async analyzeConfiguration(domain) {
        const config = {
            nameservers: [],
            redundancy: {},
            loadBalancing: false,
            geoRouting: false,
            monitoring: {}
        };
        
        // Analyze nameserver configuration
        config.nameservers = await this.analyzeNameservers(domain);
        
        // Check redundancy
        config.redundancy = {
            multipleNS: config.nameservers.length > 1,
            differentNetworks: this.checkNSDiversity(config.nameservers),
            recommended: config.nameservers.length >= 2 && config.nameservers.length <= 6
        };
        
        // Detect load balancing
        config.loadBalancing = await this.detectLoadBalancing(domain);
        
        // Detect geo-routing
        config.geoRouting = await this.detectGeoRouting(domain);
        
        return config;
    }
    
    // Analyze nameservers
    async analyzeNameservers(domain) {
        // Would fetch NS records
        // Simulated data
        return [
            {
                hostname: 'ns1.example.com',
                ip: '192.0.2.1',
                provider: 'Example DNS',
                location: 'US'
            },
            {
                hostname: 'ns2.example.com',
                ip: '192.0.2.2',
                provider: 'Example DNS',
                location: 'EU'
            }
        ];
    }
    
    // Check nameserver diversity
    checkNSDiversity(nameservers) {
        if (nameservers.length < 2) return false;
        
        // Check if nameservers are on different networks
        const networks = new Set();
        nameservers.forEach(ns => {
            if (ns.ip) {
                const network = ns.ip.split('.').slice(0, 2).join('.');
                networks.add(network);
            }
        });
        
        return networks.size > 1;
    }
    
    // Detect load balancing
    async detectLoadBalancing(domain) {
        // Make multiple requests and check if IPs change
        const ips = new Set();
        
        for (let i = 0; i < 5; i++) {
            try {
                const response = await fetch(`https://${domain}/favicon.ico`, {
                    mode: 'no-cors',
                    cache: 'no-store'
                });
                
                // Would need to check actual resolved IP
                // This is simulated
                ips.add('192.0.2.' + (i % 2 + 1));
            } catch (e) {
                // Ignore errors
            }
        }
        
        return ips.size > 1;
    }
    
    // Detect geo-routing
    async detectGeoRouting(domain) {
        // Would need to test from different locations
        // This is simulated
        return false;
    }
    
    // Detect DNS providers
    detectDNSProviders(domain) {
        const providers = {
            registrar: null,
            nameservers: null,
            cdnProvider: null
        };
        
        // Detect based on nameserver patterns
        const nsPatterns = {
            cloudflare: /cloudflare\.com$/,
            aws: /awsdns|amazonaws\.com$/,
            google: /googledomains\.com$/,
            godaddy: /domaincontrol\.com$/,
            namecheap: /registrar-servers\.com$/
        };
        
        // Would check actual NS records
        providers.nameservers = 'Unknown';
        
        return providers;
    }
    
    // Detect issues
    detectIssues(analysis) {
        const issues = [];
        
        // Performance issues
        if (analysis.performance.lookupTime > 100) {
            issues.push({
                severity: 'medium',
                category: 'performance',
                issue: 'Slow DNS lookup time',
                value: `${analysis.performance.lookupTime.toFixed(0)}ms`,
                impact: 'Delays initial connection'
            });
        }
        
        // Security issues
        if (!analysis.security.dnssec) {
            issues.push({
                severity: 'low',
                category: 'security',
                issue: 'DNSSEC not enabled',
                impact: 'Vulnerable to DNS spoofing'
            });
        }
        
        if (!analysis.security.caa) {
            issues.push({
                severity: 'low',
                category: 'security',
                issue: 'No CAA records',
                impact: 'Any CA can issue certificates'
            });
        }
        
        // Configuration issues
        if (analysis.configuration.nameservers.length < 2) {
            issues.push({
                severity: 'high',
                category: 'reliability',
                issue: 'Single point of failure',
                impact: 'No DNS redundancy'
            });
        }
        
        // Email security
        if (!analysis.security.emailSecurity.spf.present) {
            issues.push({
                severity: 'medium',
                category: 'email',
                issue: 'No SPF record',
                impact: 'Email spoofing possible'
            });
        }
        
        return issues;
    }
    
    // Generate recommendations
    generateRecommendations(analysis) {
        const recommendations = [];
        
        // Performance recommendations
        if (analysis.performance.lookupTime > 50) {
            recommendations.push({
                category: 'performance',
                priority: 'high',
                title: 'Optimize DNS performance',
                suggestions: [
                    'Use a premium DNS provider',
                    'Implement DNS prefetching',
                    'Reduce DNS lookups',
                    'Increase TTL values'
                ],
                implementation: this.generateDNSPrefetchCode()
            });
        }
        
        // Security recommendations
        if (!analysis.security.dnssec) {
            recommendations.push({
                category: 'security',
                priority: 'medium',
                title: 'Enable DNSSEC',
                description: 'Protect against DNS spoofing attacks',
                steps: [
                    'Enable DNSSEC at your registrar',
                    'Configure DS records',
                    'Verify DNSSEC chain'
                ]
            });
        }
        
        // Configuration recommendations
        if (!analysis.configuration.redundancy.recommended) {
            recommendations.push({
                category: 'reliability',
                priority: 'high',
                title: 'Improve DNS redundancy',
                suggestions: [
                    'Use 2-6 nameservers',
                    'Distribute across different networks',
                    'Consider anycast DNS'
                ]
            });
        }
        
        // Email security
        if (!analysis.security.emailSecurity.dmarc.present) {
            recommendations.push({
                category: 'email',
                priority: 'medium',
                title: 'Implement email authentication',
                records: this.generateEmailSecurityRecords(analysis.domain)
            });
        }
        
        return recommendations;
    }
    
    // Generate DNS prefetch code
    generateDNSPrefetchCode() {
        return `<!-- DNS Prefetching -->
<link rel="dns-prefetch" href="//api.example.com">
<link rel="dns-prefetch" href="//cdn.example.com">
<link rel="dns-prefetch" href="//fonts.googleapis.com">

<!-- Preconnect for critical origins -->
<link rel="preconnect" href="https://api.example.com" crossorigin>
<link rel="preconnect" href="https://cdn.example.com">

<script>
// Dynamic DNS prefetching
function prefetchDNS(url) {
    const link = document.createElement('link');
    link.rel = 'dns-prefetch';
    link.href = url;
    document.head.appendChild(link);
}

// Prefetch on hover
document.addEventListener('mouseover', (e) => {
    const link = e.target.closest('a');
    if (link && link.href) {
        const url = new URL(link.href);
        if (url.hostname !== window.location.hostname) {
            prefetchDNS(url.hostname);
        }
    }
});
</script>`;
    }
    
    // Generate email security records
    generateEmailSecurityRecords(domain) {
        return {
            spf: `v=spf1 include:_spf.google.com ~all`,
            dmarc: `v=DMARC1; p=quarantine; rua=mailto:dmarc@${domain}; pct=100; adkim=s; aspf=s`,
            dkim: `Instructions: Generate DKIM keys in your email provider`,
            mx: `Priority: 10, Server: mail.${domain}`
        };
    }
}

// Run DNS analysis
const analyzer = new DNSAnalyzer();
analyzer.analyzeDNS().then(analysis => {
    console.log('DNS Analysis:', analysis);
});

DNS Performance Monitor

Monitor DNS performance in real-time:

// DNS Performance Monitor
class DNSPerformanceMonitor {
    constructor() {
        this.metrics = {
            lookups: [],
            cache: new Map(),
            failures: []
        };
        this.startMonitoring();
    }
    
    // Start monitoring DNS performance
    startMonitoring() {
        // Monitor resource timing
        if ('PerformanceObserver' in window) {
            const observer = new PerformanceObserver((list) => {
                for (const entry of list.getEntries()) {
                    this.analyzeDNSTiming(entry);
                }
            });
            
            observer.observe({ entryTypes: ['resource', 'navigation'] });
        }
        
        // Monitor DNS prefetch
        this.monitorPrefetch();
        
        // Monitor failures
        this.monitorFailures();
    }
    
    // Analyze DNS timing from resource
    analyzeDNSTiming(entry) {
        const dnsTime = entry.domainLookupEnd - entry.domainLookupStart;
        
        if (dnsTime > 0) {
            const url = new URL(entry.name);
            const metric = {
                hostname: url.hostname,
                lookupTime: dnsTime,
                timestamp: entry.startTime,
                cached: false,
                protocol: url.protocol,
                type: entry.initiatorType
            };
            
            this.metrics.lookups.push(metric);
            
            // Update cache status
            if (!this.metrics.cache.has(url.hostname)) {
                this.metrics.cache.set(url.hostname, {
                    firstSeen: entry.startTime,
                    lookupCount: 0,
                    totalTime: 0
                });
            }
            
            const cacheEntry = this.metrics.cache.get(url.hostname);
            cacheEntry.lookupCount++;
            cacheEntry.totalTime += dnsTime;
            
            // Alert on slow lookups
            if (dnsTime > 100) {
                console.warn(`Slow DNS lookup for ${url.hostname}: ${dnsTime.toFixed(0)}ms`);
            }
        } else if (entry.domainLookupEnd > 0) {
            // DNS was cached
            const url = new URL(entry.name);
            const cached = {
                hostname: url.hostname,
                cached: true,
                timestamp: entry.startTime
            };
            
            this.metrics.lookups.push(cached);
        }
    }
    
    // Monitor DNS prefetch effectiveness
    monitorPrefetch() {
        const prefetchLinks = document.querySelectorAll('link[rel="dns-prefetch"]');
        const prefetchedDomains = new Set();
        
        prefetchLinks.forEach(link => {
            const hostname = new URL(link.href).hostname;
            prefetchedDomains.add(hostname);
        });
        
        // Check if prefetched domains are used
        setTimeout(() => {
            const usedDomains = new Set();
            
            this.metrics.lookups.forEach(lookup => {
                usedDomains.add(lookup.hostname);
            });
            
            const effectiveness = {
                prefetched: Array.from(prefetchedDomains),
                used: Array.from(usedDomains),
                unused: Array.from(prefetchedDomains).filter(d => !usedDomains.has(d)),
                unprefetched: Array.from(usedDomains).filter(d => !prefetchedDomains.has(d))
            };
            
            console.log('DNS Prefetch Effectiveness:', effectiveness);
        }, 10000); // Check after 10 seconds
    }
    
    // Monitor DNS failures
    monitorFailures() {
        // Override fetch to catch DNS failures
        const originalFetch = window.fetch;
        
        window.fetch = async (...args) => {
            const [url] = args;
            const startTime = performance.now();
            
            try {
                const response = await originalFetch(...args);
                return response;
            } catch (error) {
                const endTime = performance.now();
                
                if (error.message.includes('Failed to fetch') || 
                    error.message.includes('NetworkError')) {
                    this.metrics.failures.push({
                        url,
                        error: error.message,
                        duration: endTime - startTime,
                        timestamp: new Date().toISOString(),
                        type: 'dns_failure'
                    });
                }
                
                throw error;
            }
        };
    }
    
    // Get performance summary
    getPerformanceSummary() {
        const summary = {
            totalLookups: this.metrics.lookups.length,
            cachedLookups: this.metrics.lookups.filter(l => l.cached).length,
            uncachedLookups: this.metrics.lookups.filter(l => !l.cached).length,
            averageLookupTime: 0,
            slowestLookup: null,
            failures: this.metrics.failures.length,
            uniqueDomains: this.metrics.cache.size,
            recommendations: []
        };
        
        // Calculate average lookup time
        const uncachedLookups = this.metrics.lookups.filter(l => !l.cached && l.lookupTime);
        if (uncachedLookups.length > 0) {
            const totalTime = uncachedLookups.reduce((sum, l) => sum + l.lookupTime, 0);
            summary.averageLookupTime = totalTime / uncachedLookups.length;
            
            // Find slowest
            summary.slowestLookup = uncachedLookups.reduce((slowest, current) => 
                current.lookupTime > (slowest?.lookupTime || 0) ? current : slowest
            );
        }
        
        // Generate recommendations
        if (summary.averageLookupTime > 50) {
            summary.recommendations.push({
                issue: 'High average DNS lookup time',
                suggestion: 'Consider using a faster DNS provider or implementing DNS prefetching'
            });
        }
        
        if (summary.failures > 0) {
            summary.recommendations.push({
                issue: 'DNS resolution failures detected',
                suggestion: 'Implement fallback DNS servers and retry logic'
            });
        }
        
        const cacheRatio = summary.cachedLookups / summary.totalLookups;
        if (cacheRatio < 0.5) {
            summary.recommendations.push({
                issue: 'Low DNS cache hit rate',
                suggestion: 'Increase DNS TTL values and implement prefetching'
            });
        }
        
        return summary;
    }
    
    // Export metrics
    exportMetrics() {
        return {
            summary: this.getPerformanceSummary(),
            lookups: this.metrics.lookups,
            cache: Object.fromEntries(this.metrics.cache),
            failures: this.metrics.failures,
            timestamp: new Date().toISOString()
        };
    }
}

// Start monitoring
const dnsMonitor = new DNSPerformanceMonitor();

// Get summary after page load
window.addEventListener('load', () => {
    setTimeout(() => {
        console.log('DNS Performance Summary:', dnsMonitor.getPerformanceSummary());
    }, 5000);
});

DNS Optimization Generator

Generate DNS optimization strategies:

// DNS Optimization Generator
class DNSOptimizer {
    constructor() {
        this.optimizations = [];
    }
    
    // Generate comprehensive DNS optimizations
    generateOptimizations(domain) {
        return {
            records: this.generateOptimalRecords(domain),
            performance: this.generatePerformanceConfig(),
            security: this.generateSecurityConfig(domain),
            monitoring: this.generateMonitoringSetup(),
            implementation: this.generateImplementationGuide()
        };
    }
    
    // Generate optimal DNS records
    generateOptimalRecords(domain) {
        return {
            a_records: `; A Records - IPv4 addresses
${domain}.    300    IN    A    192.0.2.1
${domain}.    300    IN    A    192.0.2.2    ; Secondary IP for load balancing
www.${domain}.    300    IN    CNAME    ${domain}.`,
            
            aaaa_records: `; AAAA Records - IPv6 addresses
${domain}.    300    IN    AAAA    2001:db8::1
${domain}.    300    IN    AAAA    2001:db8::2`,
            
            mx_records: `; MX Records - Mail servers
${domain}.    3600    IN    MX    10    mail.${domain}.
${domain}.    3600    IN    MX    20    mail2.${domain}.`,
            
            txt_records: `; TXT Records - Various purposes
${domain}.    3600    IN    TXT    "v=spf1 include:_spf.google.com ~all"
_dmarc.${domain}.    3600    IN    TXT    "v=DMARC1; p=quarantine; rua=mailto:dmarc@${domain}"
${domain}.    3600    IN    TXT    "google-site-verification=xxx"`,
            
            caa_records: `; CAA Records - Certificate authority authorization
${domain}.    3600    IN    CAA    0 issue "letsencrypt.org"
${domain}.    3600    IN    CAA    0 issuewild "letsencrypt.org"
${domain}.    3600    IN    CAA    0 iodef "mailto:security@${domain}"`,
            
            srv_records: `; SRV Records - Service discovery
_sip._tcp.${domain}.    3600    IN    SRV    10 60 5060 sip.${domain}.
_xmpp._tcp.${domain}.    3600    IN    SRV    5 0 5222 xmpp.${domain}.`,
            
            optimization_notes: `; TTL Recommendations:
; - A/AAAA records: 300s (5 minutes) for frequently changing IPs
; - MX records: 3600s (1 hour) for mail stability
; - TXT records: 3600s (1 hour) for verification records
; - CAA records: 3600s (1 hour) for security policies
; 
; Use lower TTLs during migrations, higher TTLs for stable configurations`
        };
    }
    
    // Generate performance configuration
    generatePerformanceConfig() {
        return {
            dns_prefetch: `<!-- DNS Prefetch Configuration -->
<!-- Add to <head> section -->
<meta http-equiv="x-dns-prefetch-control" content="on">

<!-- Prefetch common domains -->
<link rel="dns-prefetch" href="//cdnjs.cloudflare.com">
<link rel="dns-prefetch" href="//fonts.googleapis.com">
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<link rel="dns-prefetch" href="//www.google-analytics.com">
<link rel="dns-prefetch" href="//ajax.googleapis.com">

<!-- API and CDN endpoints -->
<link rel="dns-prefetch" href="//api.yourdomain.com">
<link rel="dns-prefetch" href="//cdn.yourdomain.com">
<link rel="dns-prefetch" href="//images.yourdomain.com">`,
            
            preconnect: `<!-- Preconnect for critical resources -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="preconnect" href="https://api.yourdomain.com" crossorigin>`,
            
            javascript: `// Advanced DNS Optimization
class DNSOptimizer {
    constructor() {
        this.prefetchedDomains = new Set();
        this.observer = null;
        this.init();
    }
    
    init() {
        // Prefetch DNS on link hover
        document.addEventListener('mouseover', this.handleHover.bind(this), { passive: true });
        
        // Prefetch visible links
        this.observeLinks();
        
        // Prefetch based on user behavior
        this.predictivePrefetch();
    }
    
    handleHover(event) {
        const link = event.target.closest('a');
        if (link && link.href && !link.href.startsWith('#')) {
            this.prefetchDNS(link.href);
        }
    }
    
    prefetchDNS(url) {
        try {
            const hostname = new URL(url).hostname;
            
            if (!this.prefetchedDomains.has(hostname) && 
                hostname !== window.location.hostname) {
                
                const link = document.createElement('link');
                link.rel = 'dns-prefetch';
                link.href = '//' + hostname;
                document.head.appendChild(link);
                
                this.prefetchedDomains.add(hostname);
            }
        } catch (e) {
            // Invalid URL
        }
    }
    
    observeLinks() {
        if ('IntersectionObserver' in window) {
            this.observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const link = entry.target;
                        if (link.href) {
                            this.prefetchDNS(link.href);
                        }
                    }
                });
            }, {
                rootMargin: '50px'
            });
            
            // Observe all links
            document.querySelectorAll('a[href]').forEach(link => {
                this.observer.observe(link);
            });
        }
    }
    
    predictivePrefetch() {
        // Prefetch based on common user patterns
        const commonNextPages = [
            '/products',
            '/checkout',
            '/contact',
            '/about'
        ];
        
        commonNextPages.forEach(path => {
            const url = new URL(path, window.location.origin);
            this.prefetchDNS(url.href);
        });
    }
}

// Initialize optimizer
new DNSOptimizer();`,
            
            nginx_config: `# Nginx DNS Configuration
http {
    # DNS resolver configuration
    resolver 1.1.1.1 1.0.0.1 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;
    
    # DNS caching
    proxy_cache_path /var/cache/nginx/dns levels=1:2 keys_zone=dns_cache:10m max_size=1g inactive=60m;
    
    server {
        # Enable DNS prefetching hints
        add_header X-DNS-Prefetch-Control on;
        
        # Add Link headers for DNS prefetch
        add_header Link "</api.example.com>; rel=dns-prefetch" always;
        add_header Link "</cdn.example.com>; rel=dns-prefetch" always;
    }
}`
        };
    }
    
    // Generate security configuration
    generateSecurityConfig(domain) {
        return {
            dnssec: `# DNSSEC Configuration Steps

1. Enable DNSSEC at your DNS provider:
   - Generate KSK (Key Signing Key) and ZSK (Zone Signing Key)
   - Sign your zone
   - Publish DNSKEY records

2. Add DS record at your registrar:
   - Key tag: [provided by DNS provider]
   - Algorithm: 13 (ECDSAP256SHA256) or 8 (RSASHA256)
   - Digest type: 2 (SHA-256)
   - Digest: [provided by DNS provider]

3. Verify DNSSEC:
   dig +dnssec ${domain}
   
4. Monitor DNSSEC status:
   - Set up monitoring for signature expiration
   - Automate key rotation`,
            
            caa: `# CAA Record Configuration
${domain}.    IN    CAA    0 issue "letsencrypt.org"
${domain}.    IN    CAA    0 issue "digicert.com"
${domain}.    IN    CAA    0 issuewild ";"
${domain}.    IN    CAA    0 iodef "mailto:security@${domain}"

# Explanation:
# - issue: Authorize CAs to issue certificates
# - issuewild: Authorize wildcard certificates (disabled with ";")
# - iodef: Report violations to this email`,
            
            email_authentication: `# Email Authentication Records

# SPF - Sender Policy Framework
${domain}.    IN    TXT    "v=spf1 include:_spf.google.com include:_spf.sendgrid.net -all"

# DKIM - DomainKeys Identified Mail
# (Selector and key provided by email service)
selector._domainkey.${domain}.    IN    TXT    "v=DKIM1; k=rsa; p=MIGfMA0GCS..."

# DMARC - Domain-based Message Authentication
_dmarc.${domain}.    IN    TXT    "v=DMARC1; p=reject; pct=100; rua=mailto:dmarc-reports@${domain}; ruf=mailto:dmarc-failures@${domain}; fo=1"

# BIMI - Brand Indicators for Message Identification
default._bimi.${domain}.    IN    TXT    "v=BIMI1; l=https://www.${domain}/logo.svg; a=https://www.${domain}/vmc.pem"`,
            
            monitoring: `# DNS Security Monitoring

# 1. Monitor for unauthorized changes
# 2. Check for DNS hijacking
# 3. Verify DNSSEC signatures
# 4. Monitor CAA violations
# 5. Track email authentication failures

# Automated monitoring script
#!/bin/bash
DOMAIN="${domain}"

# Check DNSSEC
dig +dnssec $DOMAIN | grep -q "ad" || echo "DNSSEC validation failed"

# Check CAA
dig CAA $DOMAIN | grep -q "issue" || echo "CAA records missing"

# Check SPF
dig TXT $DOMAIN | grep -q "v=spf1" || echo "SPF record missing"

# Check DMARC
dig TXT _dmarc.$DOMAIN | grep -q "v=DMARC1" || echo "DMARC record missing"`
        };
    }
    
    // Generate monitoring setup
    generateMonitoringSetup() {
        return {
            health_checks: `# DNS Health Check Configuration

# 1. Response Time Monitoring
curl -w "DNS Lookup Time: %{time_namelookup}\\n" -o /dev/null -s https://example.com

# 2. Multi-location monitoring
LOCATIONS=("us-east" "eu-west" "ap-south")
for loc in "\${LOCATIONS[@]}"; do
    dig @8.8.8.8 example.com | grep "Query time"
done

# 3. Record consistency check
PRIMARY_NS=$(dig NS example.com +short | head -1)
SECONDARY_NS=$(dig NS example.com +short | tail -1)

diff <(dig @$PRIMARY_NS example.com) <(dig @$SECONDARY_NS example.com)`,
            
            alerts: `# DNS Monitoring Alerts

1. High Response Time Alert
   - Threshold: > 100ms average
   - Action: Check nameserver health

2. NXDOMAIN Responses
   - Threshold: Any NXDOMAIN for known records
   - Action: Verify DNS configuration

3. TTL Mismatch Alert
   - Threshold: TTL differs between nameservers
   - Action: Sync nameserver configurations

4. DNSSEC Validation Failure
   - Threshold: Any validation failure
   - Action: Check key rotation and signatures

5. Query Rate Anomaly
   - Threshold: 50% increase in query rate
   - Action: Check for DDoS or misconfiguration`,
            
            uptime_robot: `# UptimeRobot DNS Monitoring

1. Create DNS monitor:
   - Monitor Type: DNS
   - Hostname: example.com
   - DNS Server: 8.8.8.8
   - DNS Query Type: A
   - Expected Result: 192.0.2.1

2. Advanced checks:
   - Monitor multiple record types
   - Check from multiple locations
   - Verify DNSSEC validation
   - Monitor response times`,
            
            prometheus: `# Prometheus DNS Monitoring

# prometheus.yml
- job_name: 'dns_monitoring'
  static_configs:
    - targets: ['localhost:9153']
  
# DNS exporter configuration
dns_queries:
  - name: "example.com"
    type: "A"
    nameserver: "8.8.8.8"
  - name: "example.com"
    type: "MX"
    nameserver: "1.1.1.1"
    
# Alert rules
groups:
  - name: dns_alerts
    rules:
      - alert: DNSHighLatency
        expr: dns_query_duration_seconds > 0.1
        for: 5m
        annotations:
          summary: "DNS query latency high"`
        };
    }
    
    // Generate implementation guide
    generateImplementationGuide() {
        return {
            migration: `# DNS Migration Guide

## Pre-migration (1 week before)
1. Lower TTLs to 300 seconds
2. Document current configuration
3. Set up monitoring
4. Test new nameservers

## Migration Day
1. Update nameservers at registrar
2. Monitor propagation
3. Verify all record types
4. Check email delivery

## Post-migration
1. Monitor for 48 hours
2. Gradually increase TTLs
3. Update documentation
4. Remove old nameservers`,
            
            best_practices: `# DNS Best Practices

1. **Use Multiple Nameservers**
   - Minimum 2, recommended 3-4
   - Different geographic locations
   - Different network providers

2. **Optimize TTL Values**
   - A records: 300-3600 seconds
   - MX records: 3600-86400 seconds
   - TXT records: 3600-86400 seconds

3. **Implement DNSSEC**
   - Enable at provider
   - Add DS records at registrar
   - Monitor key rotation

4. **Monitor Performance**
   - Query response times
   - Propagation delays
   - Cache hit rates

5. **Security Hardening**
   - CAA records for SSL/TLS
   - SPF/DKIM/DMARC for email
   - Regular security audits`,
            
            troubleshooting: `# DNS Troubleshooting Commands

# Check DNS resolution
dig example.com
nslookup example.com
host example.com

# Trace DNS path
dig +trace example.com

# Check specific nameserver
dig @8.8.8.8 example.com

# Verify DNSSEC
dig +dnssec example.com

# Check all record types
dig ANY example.com

# Test from different locations
curl -L https://dnschecker.org/api/check/example.com

# Flush DNS cache
# macOS
sudo dscacheutil -flushcache
# Linux
sudo systemctl restart systemd-resolved
# Windows
ipconfig /flushdns`
        };
    }
}

// Generate optimizations
const optimizer = new DNSOptimizer();
const optimizations = optimizer.generateOptimizations('example.com');
console.log('DNS Optimizations:', optimizations);

Best Practices for DNS Configuration

  1. Use Anycast DNS: Automatic geographical routing
  2. Enable DNSSEC: Prevent DNS spoofing
  3. Implement CAA Records: Control certificate issuance
  4. Monitor Continuously: Track performance and security
  5. Optimize TTL Values: Balance caching and flexibility
  6. Use Multiple Providers: Avoid single points of failure
  7. Prefetch Critical Domains: Reduce lookup latency
  8. Secure Email with SPF/DKIM/DMARC: Prevent spoofing
  9. Regular Audits: Check for misconfigurations
  10. Document Everything: Maintain DNS documentation

Common DNS Mistakes

  • Single Nameserver: No redundancy for failures
  • Long TTL During Migration: Slow propagation of changes
  • Missing CAA Records: Any CA can issue certificates
  • No DNSSEC: Vulnerable to cache poisoning
  • Exposing Internal Names: Information leakage
  • No Monitoring: Blind to DNS issues
  • Missing Email Authentication: Email spoofing risks
  • Wildcard Records: Security and routing issues
  • No DNS Prefetching: Slower page loads
  • Ignoring IPv6: Missing AAAA records

Remember: DNS is the foundation of your online presence. A misconfigured DNS can take down your entire service, while an optimized DNS configuration can significantly improve performance and security.