typescript 51 lines · 8 steps

A self-refreshing feature flags provider in NestJS

A NestJS service that polls a remote endpoint on a schedule and serves cached feature flags that survive fetch failures.

Explained by highlit
1import { Injectable, OnModuleInit, Logger } from '@nestjs/common';
2import { ConfigService } from '@nestjs/config';
3import { Cron, CronExpression } from '@nestjs/schedule';
4 
5interface FeatureFlags {
6 maintenanceMode: boolean;
7 maxUploadBytes: number;
8 allowedRegions: string[];
9}
10 
11@Injectable()
12export class FeatureFlagsProvider implements OnModuleInit {
13 private readonly logger = new Logger(FeatureFlagsProvider.name);
14 private flags: FeatureFlags = {
15 maintenanceMode: false,
16 maxUploadBytes: 5_000_000,
17 allowedRegions: [],
18 };
19 
20 constructor(private readonly config: ConfigService) {}
21 
22 async onModuleInit(): Promise<void> {
23 await this.refresh();
24 }
25 
26 @Cron(CronExpression.EVERY_5_MINUTES)
27 async refresh(): Promise<void> {
28 const endpoint = this.config.getOrThrow<string>('FLAGS_ENDPOINT');
29 
30 try {
31 const res = await fetch(endpoint, { headers: { accept: 'application/json' } });
32 if (!res.ok) {
33 throw new Error(`flag service responded ${res.status}`);
34 }
35 
36 const next = (await res.json()) as FeatureFlags;
37 this.flags = Object.freeze(next);
38 this.logger.log(`Feature flags refreshed (maintenance=${next.maintenanceMode})`);
39 } catch (err) {
40 this.logger.warn(`Keeping cached flags: ${(err as Error).message}`);
41 }
42 }
43 
44 get(): Readonly<FeatureFlags> {
45 return this.flags;
46 }
47 
48 isEnabled(key: keyof FeatureFlags): boolean {
49 return Boolean(this.flags[key]);
50 }
51}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Serving from an in-memory cache means a flaky flag service never takes down the callers depending on it.
  2. 2Swallowing fetch errors and keeping the last-known-good state is a deliberate resilience choice, not a bug.
  3. 3Combining a lifecycle hook with a cron job gives you both an immediate first load and ongoing refreshes.

Related explainers

typescript
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigService } from '@nestjs/config';

How a JWT strategy authenticates in NestJS

authentication jwt passport
Intermediate 7 steps
typescript
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { BehaviorSubject, Observable, throwError } from 'rxjs';
import { catchError, filter, take, switchMap } from 'rxjs/operators';

Refreshing auth tokens in an Angular interceptor

http-interceptor token-refresh rxjs
Advanced 8 steps
php
<?php
 
namespace App\Http\Middleware;
 

Idempotent requests with Laravel middleware

idempotency middleware caching
Advanced 8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector
from django.core.cache import cache
from django.db.models import F
from django.http import JsonResponse

Ranked full-text search in Django

full-text-search debouncing caching
Advanced 9 steps
typescript
import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { GqlExecutionContext } from '@nestjs/graphql';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';

How a GraphQL auth guard works in NestJS

authentication authorization jwt
Intermediate 7 steps
python
import os
from datetime import timedelta
 
 

Class-based config in a Flask app factory

configuration app-factory inheritance
Intermediate 7 steps

Share this explainer

Here's the card — post it anywhere.

A self-refreshing feature flags provider in NestJS — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code