0
0
Expressframework~8 mins

Repository pattern for data access in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: Repository pattern for data access
MEDIUM IMPACT
This pattern affects how data fetching and manipulation impact server response time and resource usage.
Accessing data repeatedly in an Express app
Express
class UserRepository {
  constructor(model) {
    this.model = model;
    this.cache = null;
  }
  async getAllUsers() {
    if (!this.cache) {
      this.cache = await this.model.find();
    }
    return this.cache;
  }
}

const userRepo = new UserRepository(UserModel);
app.get('/users', async (req, res) => {
  const users = await userRepo.getAllUsers();
  res.json(users);
});
Encapsulates data access and caches results to avoid repeated database calls.
📈 Performance GainSingle database query reused, reducing server load and response time.
Accessing data repeatedly in an Express app
Express
app.get('/users', async (req, res) => {
  const users = await UserModel.find();
  const usersAgain = await UserModel.find();
  res.json(users);
});
Directly calling the database multiple times for the same data causes redundant queries and slows response.
📉 Performance CostTriggers multiple database queries, increasing server response time.
Performance Comparison
PatternDatabase QueriesServer CPU LoadResponse TimeVerdict
Direct DB calls in route handlersMultiple redundant queriesHigher due to repeated callsSlower due to query overhead[X] Bad
Repository pattern with cachingSingle query reusedLower CPU loadFaster response[OK] Good
Rendering Pipeline
Repository pattern affects server-side data fetching before sending response; it does not directly impact browser rendering but improves backend efficiency.
Data Fetching
Server Response Preparation
⚠️ BottleneckDatabase query execution and network latency
Optimization Tips
1Avoid redundant database queries by centralizing data access in a repository.
2Use caching inside the repository to speed up repeated data requests.
3Keep repository methods simple and focused to reduce server CPU load.
Performance Quiz - 3 Questions
Test your performance knowledge
How does using a repository pattern with caching affect server response time?
AIt has no effect on response time.
BIt increases response time by adding extra code layers.
CIt reduces response time by avoiding repeated database queries.
DIt causes more database queries to run.
DevTools: Network
How to check: Open DevTools Network tab, make the API request, and observe the number and timing of requests to the server.
What to look for: Fewer and faster server responses indicate efficient data access; multiple slow responses suggest redundant queries.