Recently worked on an interesting backend problem β sharing the approach in case it helps others working with multi-DB systems π
π§© Problem
We had two separate databases:
- Core DB β transactional data (activities, participants, items)
- Profile DB β user/entity master data + metadata
We needed:
π A unified dataset for ranking/recommendation
π Without duplicating data across databases
π‘ Solution: PostgreSQL FDW
Used Foreign Data Wrapper (FDW) to query Profile DB directly from Core DB.
CREATE EXTENSION postgres_fdw;
CREATE SERVER remote_profile_srv
FOREIGN DATA WRAPPER postgres_fdw
OPTIONS (
host 'host',
dbname 'profile_db',
port '5432'
);
π Foreign Tables
Mapped remote tables into local DB:
fdw_schema.entitiesfdw_schema.entity_detailsfdw_schema.entity_context
π Important: Convert enums β text to avoid cross-DB type issues.
π§ Data Layer Design
Built 4 layered views:
1οΈβ£ entity_profile_view
- Entity + metadata + classifications
- Handles JSON structures (like category mappings)
2οΈβ£ activity_base_view
- Core activities + configurations + rules
- Pivot configs using:
BOOL_OR(...) -- instead of MAX(boolean)
3οΈβ£ item_aggregation_view
- Extracts dynamic JSON fields
- Aggregates quantities, values, etc.
4οΈβ£ entity_activity_master_view (π₯ final)
- Joins everything
- Output = activity Γ entity dataset
βοΈ Challenge: Prisma + ENV in SQL
Prisma migrations donβt support .env inside SQL β
β Fix
Used a custom Node script to inject env values:
const finalSQL = sql
.replace(/__HOST__/g, process.env.DB_HOST)
.replace(/__DB__/g, process.env.DB_NAME);
Then executed via pg client.
ποΈ Final Architecture
Profile DB
β (FDW)
Core DB (views)
β
entity_activity_master_view
β
Ranking / ML / APIs
β‘ Key Learnings
- FDW is powerful for real-time cross-DB joins
- Always cast enums β
text - Use
BOOL_ORinstead ofMAX(boolean) - Prisma needs custom migration handling
- Views help create a clean analytical layer
π― Use Cases
- Recommendation systems
- Ranking engines
- Analytics without ETL pipelines
π₯ Takeaway
You donβt always need:
β data duplication
β complex ETL pipelines
Sometimes:
π FDW + smart SQL views = a clean and scalable solution
If you're working on distributed data systems or recommendation problems, this approach can be really useful.
Happy to discuss more π€
Top comments (0)