🏗️ Backend for Frontend (BFF) – o padrão que salvou meus microsserviços (e minha sanidade)
E aí, dev que já teve que explicar por que o frontend mobile precisa de dados diferentes do frontend web? Ou pior: já precisou adaptar uma API monolítica para atender três clientes diferentes e acabou com um endpoint que devolve 50 campos, sendo que cada frontend só usa 10? Pois é. O mundo dos microsserviços é lindo até você precisar entregar uma experiência personalizada para cada tipo de…
The Backend for Frontend (BFF) pattern provides a solution for mobile applications needing different data than web or admin interfaces. Instead of having a single backend that tries to serve all frontends, each BFF is customized for a specific frontend. For example, a BFF for web returns rich data with HTML, SEO-friendly tags, and additional fields, while a BFF for mobile returns thin payloads with essential information to save bandwidth. An admin BFF could return data for advanced permissions, reports, and other needs.
In a monolithic approach, a single endpoint might return 50 fields, but each frontend only uses a fraction of that data. This results in over-fetching, under-fetching, and large payloads that slow down mobile performance. The BFF approach solves these issues by creating a dedicated backend layer for each frontend. Each BFF fetches data from the main backend, transforms, aggregates, and filters it according to the frontend's requirements, and returns only the needed data.
To implement a BFF in practice using Spring Boot, follow these steps:
1. Create a project structure with a dedicated BFF, such as "bff-mobile," containing controllers, services, DTOs, and configuration.
2. Define a specific DTO (Data Transfer Object) for the mobile frontend. For example, a "ProdutoMobileDTO" class containing only the necessary fields for the mobile app, such as id, name, price, mini image, availability, average rating, and total ratings.
3. Create a service class that orchestrates calls to the main backend. This class, like "ProdutoMobileService," retrieves data from the backend, fetches additional data like reviews and stock availability, and assembles the DTO for the mobile frontend.
4. Use WebClient to make asynchronous API calls to the main backend for reviews and stock availability, then combine the results with the main product data to create the specific mobile DTO.
5. Set up the necessary configurations, such as WebClient configuration, for efficient communication with the main backend.
By following this pattern, you can create tailored solutions for different frontends, improving performance, reducing data transfer, and simplifying the backend architecture.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.