惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
人人都是产品经理
人人都是产品经理
V
Visual Studio Blog
Last Week in AI
Last Week in AI
V
V2EX
博客园_首页
IT之家
IT之家
Jina AI
Jina AI
博客园 - 叶小钗
The Cloudflare Blog
T
Tailwind CSS Blog
腾讯CDC
B
Blog
D
Docker
L
LangChain Blog
博客园 - 司徒正美
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
美团技术团队
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
GbyAI
GbyAI

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Protect APIs from over-fetching/under-fetching - REST vs ...
Hossein Esmati · 2026-06-26 · via DEV Community

Hossein Esmati

Best Practices Summary

For REST in .NET:

  • Use projection to DTOs (Select instead of .Include() when possible).
  • Define endpoint-specific contracts to prevent over-fetch.
  • Use AsNoTracking and async LINQ queries for read APIs.

For GraphQL in .NET:

  • Use DataLoader pattern to batch N+1 queries.
  • Limit query depth & complexity for protection.
  • Cache persisted queries when possible.

Over-fetching

  • The client receives more data than it needs.
  • Example: GET /users/1 returns the entire user entity including addresses, settings, history, but the UI only needs name and email.
  • Downsides: unnecessary CPU, bandwidth, and serialization cost.

Under-fetching

  • The client receives too little data, requiring multiple round-trips.
  • Example: GET /orders/1 returns order header only. The UI then must call /orders/1/items and /orders/1/payments.
  • Downsides: chatty APIs, high latency.

2. REST vs GraphQL

2.1) REST APIs

  • Pros:

    • Simple, mature, widely supported in .NET (Minimal APIs, ASP.NET Core MVC).
    • Strong HTTP semantics (GET/PUT/POST/DELETE, caching, status codes).
    • Easy to secure with middleware and API gateways.
    • Straightforward to implement with EF Core projections.
  • Cons:

    • Fixed shape: risk of over/under-fetching.
    • For complex UI, clients may need multiple calls.

Narrow-down DTOs, Includes, and Projections in REST

  • Narrowed-down response models designed for specific endpoints, preventing accidental over-fetch.
  • Example: UserProfileDto with only the fields needed for a profile screen.

Includes

  • In EF Core, .Include() lets you load related entities in a single query.
  • Use carefully: it prevents under-fetching but may over-fetch if you pull deep graphs unnecessarily.

Projections

  • Selecting only the needed fields directly from the DB into DTOs.
  • Example:
  var users = db.Users
      .Select(u => new UserDto(u.Id, u.Name, u.Email))
      .ToListAsync();

  • This is the most efficient pattern for REST endpoints—avoids both over-fetching and under-fetching.

2.2) GraphQL

  • Pros:

    • Client defines exactly what fields it wants (solves over/under-fetching elegantly).
    • Single endpoint can serve multiple client needs.
    • Great for frontend-heavy apps (React/Angular/Blazor with many nested queries).
  • Cons:

    • Processing cost: server parses & validates dynamic queries → heavier than REST.
    • Memory: query execution may hydrate large graphs before resolving → higher pressure than REST projections.
    • Complexity: harder caching, monitoring, and securing (need query depth limits, persisted queries, etc.).
    • In .NET (HotChocolate, GraphQL.NET): performance is good, but raw REST with EF Core projection is still faster when payload size doesn’t matter.

3. Which is Better in .NET Core

Assuming payload size is irrelevant

  • Processing time:
    REST with EF Core projection is faster because the SQL is pre-shaped and predictable. GraphQL incurs query parsing and field resolution overhead.

  • Memory usage:
    REST wins again; GraphQL’s resolver pipeline often materializes intermediate objects.

  • Raw speed (throughput):
    REST (properly designed DTO + projection) usually achieves higher RPS (requests per second). GraphQL trades some speed for flexibility.

  • When GraphQL shines:

    • Complex UI with many optional fields.
    • B2B integrations where clients vary widely in what they need.
    • Cases where reducing network calls is more important than raw speed.
  • When REST is better:

    • Internal services and backends where contracts are stable.
    • High-throughput scenarios (10M+ rows, heavy pagination).
    • APIs where performance predictability is critical.

✅ My recommendation

10M+ data, high performance, payload size doesn’t matter

  • Stick with REST + EF Core projections + keyset pagination.
  • Add GraphQL only if your consumers demand flexible queries across complex object graphs.