DEV Community

Cover image for Backend Design Patterns in NestJS: A Mobile Dev’s Learning Journey (Part 1)
Dipto Das
Dipto Das

Posted on Edited on

Backend Design Patterns in NestJS: A Mobile Dev’s Learning Journey (Part 1)

I've spent the last few years working primarily as a Flutter developer, building mobile apps. Lately, I've been looking up the stack. I want to deeply understand backend architecture, cloud infrastructure, and how AI agents are actually deployed in production.

To bridge that gap, I've been diving into NestJS and TypeScript. While building small projects and learning the framework, I realized I was writing a lot of "script-like" code. It worked, but it wasn't scalable or clean.

So I've been studying classic design patterns. Instead of just reading about them, I'm implementing them in NestJS to see how they actually solve real-world backend problems. I'm documenting this journey here to solidify my own understanding.

In Part 1, I'm looking at the Repository, Factory, and Singleton patterns. If you're also transitioning stacks or just trying to write cleaner TypeScript, I hope my notes help you out.

Note: The code snippets below are simplified for readability. Imports and some type definitions are omitted on purpose. The first line of each block is a comment showing the file it would live in.

1. The Repository Pattern: Hiding the Database

The Problem

When I first started writing NestJS services, I injected my database client (like Prisma) directly into the service.

// user.service.ts (the messy way)
@Injectable()
export class UserService {
  constructor(private prisma: PrismaService) {}

  async getUser(id: string) {
    return this.prisma.user.findUnique({ where: { id } });
  }
}
Enter fullscreen mode Exit fullscreen mode

The issue? My business logic became tightly coupled to Prisma. If I wanted to write a unit test, I had to mock the entire Prisma client. If I wanted to swap the database later, I had to rewrite my service.

The Solution

The Repository pattern creates an abstraction layer between the domain logic and the data access layer.

// user.repository.interface.ts
// 1. Define the interface (the contract)
export interface IUserRepository {
  findById(id: string): Promise<User | null>;
}
Enter fullscreen mode Exit fullscreen mode
// prisma-user.repository.ts
// 2. The concrete implementation (database-specific code)
@Injectable()
export class PrismaUserRepository implements IUserRepository {
  constructor(private prisma: PrismaService) {}

  async findById(id: string): Promise<User | null> {
    return this.prisma.user.findUnique({ where: { id } });
  }
}
Enter fullscreen mode Exit fullscreen mode
// user.service.ts
// 3. The service (clean business logic)
@Injectable()
export class UserService {
  // We only depend on the interface, not Prisma!
  constructor(@Inject('IUserRepository') private userRepo: IUserRepository) {}

  async getUser(id: string) {
    return this.userRepo.findById(id);
  }
}
Enter fullscreen mode Exit fullscreen mode

My Takeaway

It feels like extra boilerplate at first. You have to create interfaces and extra classes. But when it came time to write unit tests for my UserService, I just had to mock the IUserRepository interface. It made testing incredibly easy. The trade-off is more files, but the decoupling is absolutely worth it.

2. The Factory Pattern: Creating Objects Without the if/else Mess

The Problem

I'm fascinated by AI engineering, so I started building a feature that routes prompts to different AI models based on the user's request. My initial code looked like this:

// llm.service.ts (the messy way)
getLLMClient(provider: string) {
  if (provider === 'openai') return new OpenAIClient();
  if (provider === 'anthropic') return new AnthropicClient();
  if (provider === 'local') return new LocalLlamaClient();
  throw new Error('Unknown provider');
}
Enter fullscreen mode Exit fullscreen mode

Every time I wanted to add a new AI provider, I had to modify this core function. It violated the Open/Closed principle, which says code should be open for extension but closed for modification.

The Solution

The Factory pattern delegates the instantiation logic to a dedicated class or method. In NestJS, we can use a custom Factory Provider.

// llm-client.interface.ts
// 1. The interface
export interface ILLMClient {
  generate(prompt: string): Promise<string>;
}
Enter fullscreen mode Exit fullscreen mode
// llm-client.factory.ts
// 2. The factory
export const LLM_CLIENT_FACTORY = 'LLM_CLIENT_FACTORY';

export const llmClientFactory = {
  provide: LLM_CLIENT_FACTORY,
  useFactory: (config: ConfigService) => {
    const provider = config.get<string>('DEFAULT_LLM_PROVIDER');

    // The creation logic is isolated here
    switch (provider) {
      case 'openai': return new OpenAIClient(config);
      case 'anthropic': return new AnthropicClient(config);
      default: throw new Error('Unsupported LLM provider');
    }
  },
  inject: [ConfigService],
};
Enter fullscreen mode Exit fullscreen mode
// ai.module.ts
// 3. Using it in a module
@Module({
  providers: [
    llmClientFactory,
    {
      provide: 'ILLMClient',
      useExisting: LLM_CLIENT_FACTORY,
    },
    AIService,
  ],
})
export class AIModule {}
Enter fullscreen mode Exit fullscreen mode

My Takeaway

Factories are great for hiding complex creation logic. By moving the switch statement into a dedicated factory provider, my AIService doesn't need to know how the client is created. It just asks the DI container for the ILLMClient interface. Adding a new provider now means adding a new class, not modifying existing core logic.

3. The Singleton Pattern: NestJS Does This By Default

The Problem

In traditional Object-Oriented Programming, the Singleton pattern is often considered an anti-pattern. It introduces global state, hides dependencies, and makes testing a nightmare. You usually have to write messy private constructors to enforce it.

The Solution (NestJS Context)

Here's a cool realization I had while learning NestJS: NestJS uses the Singleton pattern by default for all providers.

When you create a service in NestJS and inject it into three different controllers, NestJS doesn't create three instances. It creates one instance and shares it across the entire application lifecycle.

// cache.service.ts
@Injectable()
export class CacheService {
  private cache = new Map<string, string>();

  set(key: string, value: string) {
    this.cache.set(key, value);
  }

  get(key: string) {
    return this.cache.get(key);
  }
}
Enter fullscreen mode Exit fullscreen mode

Because CacheService is a Singleton in NestJS, if Controller A sets a value in the cache, Controller B can read it. They are sharing the exact same instance in memory.

My Takeaway

While "manual" Singletons (like the classic private static instance) are usually a bad idea, framework-managed Singletons (like NestJS Dependency Injection) are incredibly powerful.

  • When it's good: Database connections, caching services, configuration loaders.
  • When it's bad: If your service holds temporary, request-specific state. (If you need a new instance per request, look into NestJS REQUEST-scoped providers.)

Wrapping up Part 1

Transitioning from mobile to backend has been a steep learning curve, but understanding these patterns is finally making the architecture click for me. Writing this out is helping me solidify the concepts, and I hope it helps someone else along the way.

Next up in Part 2, I'll be tackling the Strategy, Observer, and Builder patterns.

I'm documenting this as I learn, so if you spot any anti-patterns, edge cases I missed, or just have a cleaner way to write this in NestJS, please call it out in the comments. Always looking to level up.

Cover photo by Fotis Fotopoulos on Unsplash

Top comments (0)