Table of Contents

GraphQL API Architecture in Graph API

A Brief Overview

GraphQL is a dynamic and powerful query language that gives clients precise control to request backend data. Unlike REST APIs, GraphQL reduces over fetching and under fetching data that often happen when clients must call multiple endpoints or make several network requests, and it often performs better for mobile and complex applications by returning the exact data needed. It also accelerates front-end development. To achieve this, GraphQL requires careful schema design. GraphQL adds server complexity, and adds performance, caching, and authorization challenges for the backend. It also requires detailed operational practices and security configuration.

GraphQL

GraphQL is a recently developed specification. It was initially developed by Facebook in 2012. In 2015, the draft specification and open-source implementation were released publicly. Since 2018, the GraphQL project has been managed by GraphQL Foundation, and hosted by the Linux Foundation.

What is GraphQL?

GraphQL is a data query and manipulation language that allows the client to specify which data should be queried and/or modified. GraphQL models data as a graph where Resources are represented as Nodes and their relationships are illustrated as an Edge. GraphQL supports reading, writing, and subscribing to changes made to data.

  • GraphQL is a data-centric API that has defined structures for data, and queries define what data is required. This enhances efficiency and scalability of API as only the required data is fetched.
  • GraphQL provides greater control over the data as per client requirement and enables clients to get only the required data, reducing calls made by the client to the server.
  • GraphQL server gathers data from various sources and returns it to the client by processing data requests that it has received from the client. This would result in more flexible communication between the client and server via a reduced number of endpoints.

GraphQL APIs are implemented via HTTP Requests, and typically it has a single endpoint for communication. GraphQL lets clients define the content or information required in response, and it can also be layered on top of existing REST APIs.

GraphQL Schema

A GraphQL schema is the essence of Graph API. A well-defined schema is crucial for the operation of GraphQL, and the schema defines the API contract, including types, fields, and operations. The data represented in schema is defined as entities (nodes) and their relationships (edges). The Schema outlines what information can be retrieved or how it can be manipulated through the available Graph API.

In GraphQL, the definition of schema is critical for success or failure of API. It is essential for the schema to feature well-defined entities and relationships that can be accessed via Graph API.

In GraphQL, Schemas are written in Schema Definition Language (SDL). SDL is used to outline types along with their properties and data types of properties, as well as the queries, mutations, and subscription that API supports.

Introspection queries let clients inspect the schema, and this capability is enabled by default in many GraphQL implementations. Attackers can use that schema discovery to uncover sensitive data or internal operations, so production systems should disable introspection when public schema discovery is unnecessary.

Components of SDL

Type

A ‘Type’ in Schema is defined as entities, relationships and allows operations for data in schema. It specifies the data model or data structure acceptable for API requests. It specifies allowed properties and their respective data types. Data types for properties can be one of the built-in data types like Int, Float, String, Boolean, or any Type defined in Schema. It helps to define Enums, Interface, Unions, or Input for Object too. Clients can utilize these defined types to construct Queries and Mutations for API calls.

Query

A ‘Query’ is an operation type used by the client to get data from the server. A query uses the Type defined in the schema to retrieve specific data. Queries are defined in the Schema and implemented by the server. A query is a schema-defined, client-invoked read operation containing types as fields and arguments, where the query structure guides data fetching and lets clients ask for exact data.

Mutation

GraphQL allows clients to modify data, including creating, updating, or deleting records, and access control matters for these operations. Mutation holds a variable that needs to be processed by server for client. Mutation helps to write or delete models or values. Mutation also can share what data should be returned as response once the mutation is done.

Subscriptions

GraphQL provides support to send live updates to clients from the server. It enables servers to push real-time updates to the client. Clients can subscribe to defined subscriptions. Clients can define the format and required data as part of the subscription request.

Benefit of GraphQL

  • Schema Definition: A schema is defined from the initial stage of the development cycle. It provides a well-defined structure of entities and relationships between data. This helps the client avoid errors by validating received data against the schema, as GraphQL is strongly typed and can return clearer error messages before data is fetched.
  • Declarative Data Representation: Data is represented as a graph using entities and relationships in schemas that represent the data model as a graph. The well-structured schema allows the client to specify the types, attributes, and relationships required for the response.
  • Efficient Data Transfer: An API response contains all necessary types, attributes, and relationships required by the client. This approach will help to eliminate over-fetching and under-fetching in response, ensuring that all necessary data is received through the defined request. As a result, it will minimize the number of calls needed to gather all the required information.
  • Connected Data Queries: The API response is generated based on requested information from the client. The GraphQL is designed to retrieve related information from multiple sources, allowing queries to retrieve related data across network resources as defined in the schema for the type and its relationships.
  • Reduced Calls: Clients have the ability to request the required information in a fetch query to the server. This approach allows the client to define all requested information and collect all of it into a single query. Thus, it eliminates the requirement for multiple calls to the server by the client to just one call.
  • Ease of Data Processing: GraphQL schemas are well defined for types and their relationships for every attribute. Clients can carry out response processing according to the defined schema, enabling them to carry out data validation and verification with the schema. This methodology enhances the efficiency of data processing on the client side. During the integration with the backend, clients can validate the incoming data against the schema to ensure its validity to avoid processing issues. Explicit error handling in schema and resolver design also helps clients process failures consistently.
  • Reduced Endpoints: A single endpoint will be responsible for handling the requested data as outlined by the GraphQL Schema, in accordance with the relevant HTTP Method. This includes using GET to retrieve data, POST to create new entries, PUT/PATCH to update existing resources, and DELETE to remove them.

Drawback of GraphQL

  • Schema Definition: Altering a GraphQL schema is an intricate process that requires preserving backward compatibility. Incomplete or erroneous change in schema definition may not be able to keep up with pace of change in requirements, and it could have a negative impact on the performance of the API. Frequent, faster, and shorter release and requirement change (such as in Agile Workflow) further increases the complexity and makes schema evolution more challenging.
  • Performance: Performance of the Graph API is determined by how the Schema is defined. Any incorrect types, misconfigured relationships, or unsuitable relationship depth can slow down request processing. Furthermore, issues in relationship validation can have an adverse effect on the overall performance of the GraphQL API.
  • Complexity: GraphQL relies on accurate schema definition and implementation of this schema. Furthermore, the initial setup of a GraphQL server, along with schema configuration, can be more complex. Developers might need time to familiarize themselves with the newer technology and the best practices pertaining to GraphQL.
  • Security of Data: The system operates on a single primary endpoint. Types and relationships referenced in queries and mutations must be validated at multiple stages to ensure no requested data violates restrictions assigned to clients. The system must implement comprehensive and intricate validation processes and alerting mechanisms to maintain data integrity and security.
  • Control over Data: Types and relationships requested through queries and mutations may be deep and potentially violate the security restrictions applicable to clients. Requests for deep types and relationships can require additional time to generate responses and may result in service disruptions; this is also a concern from a security perspective of the system.
  • Caching: GraphQL queries vary by request, making traditional caching methods ineffective, because cached responses rarely match later queries. This will require a tailored caching strategy to improve performance for incoming requests.
  • Monitoring of resource: A single request can contain multiple entities targeting the same endpoint, complicating the enforcement of observability and rate limiting on a per-client basis. Implementation of observability and rate-limiting requires additional mechanisms, increases resource utilization, and may overload the backend.
  • Learning curve: GraphQL is a relatively recent concept that requires teams to develop a comprehensive understanding to fully benefit from its capabilities. Developers will likely need to spend extra time familiarizing themselves with GraphQL concepts and best practices. Additionally, there may be a need for improvements or updates to the automation framework for testing purposes.
  • Client Complexity: The client requires a complete understanding of the schema. The client needs to construct more complex query requests and traverse entities and relationships after receiving responses. This requires clear mapping of entity structures and relationships from schema for accurate navigation.

Real-world GraphQL Vulnerabilities: Incidents and Resolutions

There have been incidents involving GraphQL APIs.

Data Harvesting:

  • Incident: Third-party app was able to collect social media data of millions of users, and it was used for user profiling
  • Impact: Privacy breach, that impacted user trust on organization. Multimillion dollar fine was imposed, and there were regulatory scrutinies around it.
  • Reason: Excessive permission or insufficient check allowed broader access to social media data without user consent
  • Prevention: The scope of access should be reduced; token life should be shorter; and requests must be monitored.


Oversharing Information:

  • Incident: Apps with broader OAuth Access Tokens accessed Graph-style API endpoint that shared PII information, along with contact, messages, and calendar information and potentially data leaking and the data was sold.
  • Impact: Large scale personal data breach and privacy violation took place, and that lead to the threat of identity theft. It had an impact on brand trust.
  • Reason: It increased the privacy risk of users, and it would make it easier to identify users by accessing these data.
  • Prevention: The scope of access should be reduced; token life should be shorter; and requests must be monitored.


Misconfigured Enterprise Data

  • Incident: Graph API containing information about organization structure, including employee details, organization hierarchy, contact details, etc., were exposed to external low privilege apps.
  • Impact: Organization was targeted for social engineering, targeted phishing. It exposed internal organizational data.
  • Prevention: Access to resources and relationships for requested APIs should be configured based on requesting client and limit its access to network services for Graph API with proper Authorization checks.


Degradation and Denial of Outage

  • Incident: The client issued deep and recursive requests that caused heavy load on backend services that degraded performance leading to denial of service
  • Impact: Recursive calls and deep data query consumed higher resources, like the CPU, Memory, I/O, and that overwhelmed the servers and led to unavailability of service to customer and outage of service.
  • Reason: Misconfigured limits for depth in response to requests along with the relation to access request. Cost of queries were not calculated, and throttling was not configured and that lead to a higher number of relations with deep data requests.
  • Prevention: Limits for depth and relationships must be placed on the query based on the cost of the query, with depth limiting and query cost analysis. Also, timeouts and quotas should be applied to queries, since attackers may abuse GraphQL aliases to request multiple object instances in one call.


Data Loss

  • Incident: Bug or malicious client performed large scale data deletion and updates across multiple resources causing massive data loss and data in an inconsistent state.
  • Impact: Data loss and data integrity issues in data relationships. It increased recovery time resulting in revenue and trust loss for organization.
  • Reason: APIs allow requests to manipulate or delete multiple records and batch with limited safeguard against data manipulation and deletion. Limit for operations was too high or not configured at all.
  • Prevention: There must be attribute and relation level safeguards in place. It should also have a limit for batch in terms of manipulation and deletion of any data, and mutations can modify data across many records so authorization logic must be enforced per resolver. For deletion, there must be a confirmation process in place to avoid such destructive operations.


Query Injection (CVE class vulnerability)

  • Incident: Malformed requests injected Graph Query Language and/or Database queries to access data and privilege escalation.
  • Impact: Clients got unauthorized access, and data breach took place. It also allowed clients to get data available inside networks that are not accessible to external clients.
  • Reason: Request sanitization, validation, and access to attributes were not implemented to restrict these activities. Broken Object Level Authentication is a common GraphQL vulnerability.
  • Prevention: All user input must be validated and sanitized, and database access should use parameterized queries to block sql injection and related manipulating queries. Web Application Firewalls (WAFs) should be configured to protect graph queries via filtering and monitoring HTTP traffic to prevent such attacks. Also, Intrusion Detection Systems (IDS) should be in place to identify such attacks and generate alerts for the same.


Stale Caching

  • Incident: Intermediatory cached information was shared after removal of access to associated access tokens.
  • Impact: Unauthorized access to available data and privacy violations.
  • Reason: Time-to-Live (TTL) was longer for relationship cache; caching was not invalidated based on change in access for relationships. No revalidation was happening for critical relationships.
  • Prevention: Shorter TTL and event-driven cache invalidation should be configured. Also, validation of relations based on access configuration must be performed for request before returning cached information


Observability and Audit Blind spots

  • Incident: Delays in issue detection and investigation and incomplete information to generate regulatory reports.
  • Impact: Delays in issue detection, reporting, and investigation. Incident responses were slow, and root cause analysis (RCA) did not contain information about critical relationship accesses. It caused issues of regularity reporting.
  • Reason: Graph Queries did not generate required audit and access patterns; log related to relationships. 
  • Prevention: Structured, high-fidelity audit logs must be generated for graph API requests. Audit trails should be preserved based on mandatory retention periods. It is better to add metrics for request patterns that would help to calculate costs too and to add sampling of high-volume requests, and teams should test GraphQL APIs regularly to uncover security gaps in GraphQL services, because such tools help identify them.

Frequently Asked Questions – GraphQL API: Architecture

  1. What are the components of GraphQL?
    Type, Query, Mutation, and Subscription are components of GraphQL
  2. What is Node and Edge in GraphQL Schema?
    Node: Resources and/or Entities are called Node in GraphQL Schema
    Edge: Relationship between Nodes are called edge in GraphQL Schema
  3. Why introspection queries should be disable on production?
    Attackers can use introspection queries to identify edges and relationships. They can uncover sensitive information available in application and internal operations.
  4. What is resolver function?
    Resolver function fetches data for defined type defined in Schema.

Authors

Nimesh N Bhuva
AUTHOR

Nimesh Bhuva

Nimesh H Bhuva is a Technical Architect at eInfochips. He completed his master's degree in computer applications at Sardar Patel University and brings over ten years of experience in application design. His project designs range from basic single-node setups to complex monolithic and distributed services, as well as cutting-edge microservice-based solutions. He has a strong track record of designing and developing high-performance, highly available, fault-tolerant, scalable, and flexible application services that fulfill the specific expectations of our partners and clients.

Explore More

Talk to an Expert

Subscribe
to our Newsletter
Stay in the loop! Sign up for our newsletter & stay updated with the latest trends in technology and innovation.

Download Report

Download Sample Report

Download Brochure

Start a conversation today

Schedule a 30-minute consultation with our Automotive Solution Experts

Start a conversation today

Schedule a 30-minute consultation with our Battery Management Solutions Expert

Start a conversation today

Schedule a 30-minute consultation with our Industrial & Energy Solutions Experts

Start a conversation today

Schedule a 30-minute consultation with our Automotive Industry Experts

Start a conversation today

Schedule a 30-minute consultation with our experts

Please Fill Below Details and Get Sample Report

Reference Designs

Our Work

Innovate

Transform.

Scale

Partnerships

Device Partnerships
Digital Partnerships
Quality Partnerships
Silicon Partnerships

Company

Products & IPs

Privacy Policy

Our website places cookies on your device to improve your experience and to improve our site. Read more about the cookies we use and how to disable them. Cookies and tracking technologies may be used for marketing purposes.

By clicking “Accept”, you are consenting to placement of cookies on your device and to our use of tracking technologies. Click “Read More” below for more information and instructions on how to disable cookies and tracking technologies. While acceptance of cookies and tracking technologies is voluntary, disabling them may result in the website not working properly, and certain advertisements may be less relevant to you.
We respect your privacy. Read our privacy policy.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.