Optimizing Mobile and Web Apps with Backend for Frontend (BFF) Pattern

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.

Development and maintenance of all types of websites:

Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Showing 1 of 1All 2062 services
Optimizing Mobile and Web Apps with Backend for Frontend (BFF) Pattern
Complex
~2-4 weeks
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1364
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1253
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    959
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1191
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    933
  • image_bitrix-bitrix-24-1c_fixper_448_0.webp
    Website development for FIXPER company
    950

A mobile app makes 5–10 sequential HTTP requests to load a single page. On a mobile network, each round trip adds 200–500 ms — totaling up to 2–3 seconds. Typical scenario: /users/{id}, /orders?userId={id}&limit=3, /notifications/unread, /recommendations?userId={id}, /loyalty/points/{id}. The client must wait for all responses and perform transformations. This is not only slow but also consumes excess traffic: loading unnecessary fields (e.g., full address when viewing the cart) increases the volume of transmitted data by 30–50%. We propose introducing an intermediate Backend for Frontend (BFF) layer. Savings on traffic and infrastructure can reach 40% after BFF implementation, with typical savings of $2,000 per month on cloud costs.

BFF is a separate backend service created for a specific client type (web, mobile app, Smart TV). It accepts one request from the client, simultaneously queries the necessary microservices, aggregates data, strips unnecessary fields, and returns the result in a format optimal for that client. The concept is detailed in Martin Fowler's article the original article.

What Problems Does BFF Solve?

N+1 requests and latency. A typical picture: 5–10 sequential calls for one page. BFF reduces this to one call by executing parallel requests to services. Time savings — up to 80% of round trips (4x faster than direct client calls).

Excessive data. A microservice returns fields the client doesn't need (e.g., address when viewing a cart). BFF strips unnecessary data, reducing the volume of transmitted data by 30–50% (e.g., from 150 KB to 80 KB per screen).

Complex authentication. JWT, refresh token, httpOnly cookie — BFF manages sessions centrally without exposing services from the client.

Partial failures. If one service is unavailable, BFF can return a partial response (null for the failed fragment) instead of a 500 error, using retry logic with exponential backoff.

Caching common data. Placing BFF between the client and services allows caching aggregated responses (e.g., recommendations), reducing load on microservices by 40%.

How We Implement BFF: Stack and Examples

In practice, BFF is convenient to build on Node.js with Express or Apollo Server (GraphQL). In our projects we use Node.js, TypeScript, Express or Apollo Server, Redis for caching (ioredis), and axios for HTTP requests.

Example for Mobile App

One endpoint /mobile/dashboard is required, returning profile, recent orders, notifications, and loyalty points.

// mobile-bff/routes/dashboard.ts
router.get('/mobile/dashboard', authenticate, async (req, res) => {
  const userId = req.user.id;

  const [userResult, ordersResult, notificationsResult, loyaltyResult] =
    await Promise.allSettled([
      userService.get(`/users/${userId}`),
      orderService.get(`/orders?customerId=${userId}&limit=3&fields=id,status,total,createdAt`),
      notificationService.get(`/notifications/${userId}/unread-count`),
      loyaltyService.get(`/loyalty/${userId}/summary`)
    ]);

  const response = {
    user: userResult.status === 'fulfilled' ? {
      id: userResult.value.data.id,
      name: userResult.value.data.displayName,
      avatar: userResult.value.data.avatarUrl
    } : null,
    recentOrders: ordersResult.status === 'fulfilled'
      ? ordersResult.value.data.items.map(transformOrderForMobile)
      : [],
    unreadCount: notificationsResult.status === 'fulfilled'
      ? notificationsResult.value.data.count
      : 0,
    loyalty: loyaltyResult.status === 'fulfilled' ? {
      points: loyaltyResult.value.data.balance,
      tier: loyaltyResult.value.data.tier
    } : null
  };

  res.json(response);
});

Example for Web Client

A web client needs the same data but with a full profile, a larger order list, and analytics.

// web-bff/routes/dashboard.ts
router.get('/web/dashboard', authenticate, async (req, res) => {
  const userId = req.user.id;

  const [user, orders, stats, notifications] = await Promise.allSettled([
    userService.get(`/users/${userId}`),
    orderService.get(`/orders?customerId=${userId}&limit=10`),
    analyticsService.get(`/analytics/user/${userId}/stats`),
    notificationService.get(`/notifications/${userId}?limit=5&unread=true`)
  ]);

  res.json({
    user: user.status === 'fulfilled' ? user.value.data : null,
    orders: orders.status === 'fulfilled' ? orders.value.data : { items: [], total: 0 },
    analytics: stats.status === 'fulfilled' ? stats.value.data : null,
    notifications: notifications.status === 'fulfilled' ? notifications.value.data : []
  });
});
Expand example for GraphQL BFF
// web-bff/graphql/schema.ts
const typeDefs = gql`
  type Query {
    dashboard: Dashboard!
    order(id: ID!): Order
  }

  type Dashboard {
    user: User!
    recentOrders: [Order!]!
    stats: UserStats!
  }
`;

const resolvers = {
  Query: {
    dashboard: async (_, __, { userId }) => {
      const [user, orders, stats] = await Promise.all([
        userService.getUser(userId),
        orderService.getRecentOrders(userId),
        analyticsService.getUserStats(userId)
      ]);
      return { user, recentOrders: orders, stats };
    }
  }
};

How to Implement Authorization and Caching in BFF?

BFF is a natural place for centralized authorization and caching. JWT token is verified at the BFF level, refresh token is stored in an httpOnly cookie (for web clients), and Redis cache speeds up responses for rarely changing data.

// authorization middleware
router.post('/auth/refresh', async (req, res) => {
  const refreshToken = req.cookies.refresh_token;
  if (!refreshToken) return res.status(401).json({ error: 'No token' });
  const tokens = await authService.refreshTokens(refreshToken);
  res.cookie('refresh_token', tokens.refreshToken, {
    httpOnly: true, secure: true, sameSite: 'strict',
    maxAge: 30 * 24 * 60 * 60 * 1000
  });
  res.json({ accessToken: tokens.accessToken });
});

// caching with Redis
import Redis from 'ioredis';
const redis = new Redis(process.env.REDIS_URL);

async function getCachedOrFetch<T>(key: string, ttl: number, fetcher: () => Promise<T>): Promise<T> {
  const cached = await redis.get(key);
  if (cached) return JSON.parse(cached);
  const data = await fetcher();
  await redis.setex(key, ttl, JSON.stringify(data));
  return data;
}

Choosing Between GraphQL and REST for BFF

If the client is a React app with Apollo Client, BFF can expose a GraphQL schema. This allows the client to request exactly the needed fields without duplicating endpoints. GraphQL BFF is especially useful when data requirements change frequently: the client controls the fetching. However, for simple mobile apps with fixed screens, REST BFF is often more efficient due to lower complexity.

What's Included in the Work

  • Audit of the current architecture and identification of frequent round trips.
  • Design of a BFF layer for each client (REST or GraphQL).
  • Development of APIs with data aggregation and transformation.
  • Implementation of authorization (JWT, session-based).
  • Caching with Redis or in-memory.
  • Error handling and partial failures (Promise.allSettled).
  • Documentation (OpenAPI or GraphQL SDL).
  • Testing and load testing.
  • Deployment (Docker, Nginx, Vercel, AWS Lambda).

Timelines

BFF Type Timeline Cost Range
REST BFF for 1 client (3–5 endpoints) 1–2 weeks $5,000 – $10,000
GraphQL BFF + authorization + caching 2–3 weeks $10,000 – $15,000
BFF for 2–3 clients with shared library 3–4 weeks $15,000 – $20,000

Work Process

  1. Analysis – study the request pattern and identify bottlenecks.
  2. Design – define the set of aggregated endpoints and the stack.
  3. Implementation – write the BFF layer, caching, and authorization.
  4. Testing – unit, integration, and performance tests.
  5. Deployment – deploy and set up monitoring.

Typical Mistakes When Implementing BFF

  • Duplicating logic – each BFF duplicates transformations. Solution: extract common functions into a shared library.
  • Monolithic BFF – one BFF for all clients leads to the same problems as a unified API. Each client should have its own BFF.
  • Ignoring partial failures – if one service fails, BFF should not crash. Use Promise.allSettled with circuit breaker pattern.
  • Lack of caching – without cache, every request hits the services, increasing load and response time.

Why Does BFF Outperform a Unified API?

Without BFF, the client must aggregate data itself, leading to excessive requests and complicated client logic. BFF handles orchestration: one request from client → parallel queries to microservices → aggregation → transformation → response. This speeds up loading (4x faster), reduces traffic (46% less), and simplifies maintenance.

Our Experience

We implemented BFF for a large e-commerce project. Results:

Metric Without BFF With BFF
Number of requests per screen 7 1
Load time 3.2 s 0.8 s
Traffic per screen 150 KB 80 KB
Load on services 100% ~60%

Experience of our engineers: 8+ years in microservice architecture. Order BFF development starting from $5,000 and get guarantees on response time and fault tolerance. Contact us for a free consultation – we'll evaluate your project in 1–2 days. Order BFF development and get optimization tailored to your client.

Backend Development Services: Laravel, Node.js, Go, Django, PostgreSQL

On a production server at 3:14 AM, the Laravel Jobs queue stopped processing. 40,000 unprocessed jobs in Redis. Cause: worker crashed due to a memory leak in one of the Jobs (leak via a static variable in an Eloquent observer), supervisor didn't restart it because of misconfigured stopwaitsecs. This is not a hypothetical scenario — it's Tuesday. We analyzed such an incident on a project with 500 RPS load: diagnosis took 4 hours, fix — 20 minutes. So you don't lose money on downtime, we offer backend development services with a focus on production-grade reliability. We'll assess your project in 2 days.

Backend is what works when no one is watching. Or doesn't work. We guarantee you'll have the first option.

How do we ensure production-grade reliability from day one?

What we do correctly from day one

Service Layer over Fat Controllers. Controller receives HTTP request, validates it via Form Request, passes data to Service, returns response. Business logic in Service, not Controller. This sounds trivial, but most legacy projects have controllers with 500 lines and SQL queries inside.

Repository Pattern we use cautiously. If you just wrap Model::where(...) in a repository method — that's boilerplate without benefit. Repository is justified when: you need to abstract from the data source (DB + cache + external API) or when query logic is complex enough to isolate.

Jobs, Events, Listeners. Everything that can be async — make async. Sending email, PDF generation, external API sync, aggregate recalculation — into Queue. Laravel Horizon for queue monitoring in Redis: see throughput, failed jobs, processing time per queue.

How Octane handles high load

Laravel Octane with RoadRunner or Swoole keeps the app in memory between requests — removes bootstrap overhead (config loading, class autoloading) on each HTTP request. Gain: 3–8x on synthetic benchmarks, 2–4x on real applications. Important: no state between requests in static variables — that leads to exactly the incidents from the beginning. We use this in projects with >1000 RPS.

What to do about N+1 queries

N+1 is the most common cause of slow pages in Laravel apps. Standard story: page worked fine on dev with 10 records, on production with 10,000 — 8-second load.

Laravel Debugbar in dev environment shows the number of queries per page. More than 20 queries per page — signal for audit.

Model::preventLazyLoading(! app()->isProduction());

Telescope for profiling in staging: logs all queries, jobs, mail, notifications with time detail. Numbers: after implementing eager loading, page load time drops from 8s to 0.3s — 27 times faster.

PostgreSQL: indexes that are actually needed

PostgreSQL 14+ is the primary DB on all projects. We use PgBouncer + PostgreSQL combination. 10+ years experience, more than 50 backend projects, 5 years on the market.

How PostgreSQL helps avoid slow queries

Composite indexes for frequent WHERE + ORDER BY. If you have WHERE user_id = ? AND status = ? ORDER BY created_at DESC — you need (user_id, status, created_at DESC). A separate index on (user_id) doesn't help much with sorting.

Partial indexes. If 95% of queries go with WHERE status = 'active':

CREATE INDEX idx_orders_active ON orders (created_at DESC)
WHERE status = 'active';

The index is small, fast, covers the main load.

GIN indexes for JSONB and arrays. @> operator without GIN index — seq scan. With index — fast even on millions of rows.

GIN for full-text search. to_tsvector + GIN instead of LIKE '%query%'. LIKE without index is always seq scan. With pg_trgm extension and gin_trgm_ops — supports LIKE with index, useful for CRM search by partial match.

Connection pooling: why it's more important than it seems

Rails, Laravel, Django open a new connection to PostgreSQL for each PHP/Python process. With 100 workers — 100 connections. PostgreSQL starts degrading from 200–300 active connections — overhead on connection management becomes significant.

PgBouncer — connection pooler in front of PostgreSQL. Transaction pooling mode: connection to PostgreSQL is occupied only during a transaction, returned to pool between requests. 1000 application workers → 20–50 actual connections to PostgreSQL. This reduces latency by 40% and hosting costs by 30%.

Node.js with Fastify: when it's better than Laravel

Node.js is justified for:

  • Realtime: WebSocket servers, Server-Sent Events, chat, live updates
  • Streaming: large files, video, streaming data
  • High I/O concurrency: many parallel requests to external APIs without heavy business logic
  • Serverless: Lambda/Cloud Functions — Node.js starts faster than PHP

Fastify over Express: 2–3 times faster on benchmarks, built-in JSON Schema validation, better TypeScript support, plugin architecture.

Typical realtime architecture: Laravel — core business logic and REST API. Node.js + Socket.io or ws — WebSocket server. Laravel publishes events to Redis Pub/Sub, Node.js subscribes and broadcasts to clients. This separation allows scaling the WebSocket server independently of the main app.

Go: microservices and high load

Go we use for:

  • High-load microservices (>10,000 RPS)
  • Background workers with strict latency requirements
  • DevOps tools and CLI
  • gRPC services in microservice architecture

Goroutines — thousands of times cheaper than OS threads. 10,000 concurrent connections on Go is normal on one server.

But Go is not a silver bullet. Development is slower than Laravel: more boilerplate, no ORM at Eloquent level, error handling with if err != nil everywhere. Justified only when performance is a real requirement, not an assumption.

Django and Python backend

Django with DRF (Django REST Framework) — for tasks where Python is needed: ML pipelines, data processing, integrations with AI tools.

Celery for background tasks — similar to Laravel Queue but more complex to configure. Celery Beat for cron tasks.

Django ORM vs raw SQL: ORM is convenient for CRUD. For analytical queries with multiple JOINs, window functions, and CTEs — connection.execute() with raw SQL is more readable and predictable.

Redis: not just cache

Redis in our projects plays multiple roles:

Role Details
Cache Caching results of heavy queries, HTML fragments
Queues Backend for Laravel Queue / Celery
Session store Distributed sessions in multi-instance environment
Pub/Sub Realtime events between services
Rate limiting Sliding window counters for API throttling
Leaderboards Sorted Sets for rankings

Redis Cluster for horizontal scaling. Sentinel for automatic failover on standalone setups.

Deployment and infrastructure

Docker + docker-compose — standard for local development and production. Each service in a container: PHP-FPM/Octane, Nginx, PostgreSQL, Redis, Queue Worker, Scheduler.

CI/CD via GitHub Actions:

  1. Run tests (PHPUnit / Pest, Vitest, Playwright)
  2. Build Docker image
  3. Push to Container Registry
  4. Deploy: docker pull → docker-compose up -d on server, or Kubernetes rolling update

Zero-downtime deploy for Laravel: php artisan down --secret=TOKEN is not needed with proper configuration. Strategy: new container starts next to the old one, Nginx switches traffic after health check, old container stops.

Monitoring: Sentry for exception tracking with alerting in Slack/Telegram. Grafana + Prometheus (or Grafana Cloud) for metrics: CPU, memory, request rate, queue depth, database connection count. Alerts on: error rate > 1%, p99 latency > 2s, queue depth > 1000 jobs.

What's included in turnkey work

  • Architecture design (API documentation, DB schema, service diagram)
  • Implementation according to agreed specification with code review
  • CI/CD, monitoring, alerting setup
  • Load testing (k6, wrk) with report
  • Handover of source code, access, deployment instructions
  • Training of customer's team (2-3 sessions)
  • Warranty support for 1 month after delivery

Timeline benchmarks

Task Timeline
REST API for mobile/SPA (medium complexity) 6–12 weeks
Backend with complex business logic + integrations 12–20 weeks
High-load service on Go 8–16 weeks
Migration from legacy PHP to Laravel 16–32 weeks

Pricing is calculated individually after analyzing load, integrations, and business logic. Contact us for a free audit of your current backend — get an optimization plan in 2 days. Request a consultation.