BackendEstudos atuais11 de novembro de 2026

Redis

Nesse Resumo breve irei mostrar para vocês a melhor forma de utilizar Redis no backend em conjunto com NestJs

Por Gustavo Lima de Lucena

o primeiro passo para começar com Redis e fazer a instalação dele com o comandos

Bash
npm i --save ioredis

O que iremos implementar Hoje e um OTP storage que serve para criar a confirmaçao de contas ou para redefinir senhas

o usuario vai digitar o email dele --> iremos criar o OTP (hash), com o TTL(time to Live) de (1min)

OTP(one time password)

podemos também definir um cooldown time que servira como proteção para que o usuario nao tente criar ataques de bruteForce ou seja o cooldown ira aumentar o tempo que ele podera tentar fazer uma request de OTP

A forma de fazer isso e

redis
otp:email -> otp(hash), TTL (1min)

cooldown:email -> cooldown, TTL (>cooldown)

retry: eamil -> retry_counts, TTL

![[Screenshot 2026-11-11 at 12.24.38.png]]

A definiçao das variaveis e feita da forma acima

Repare que utilizamos a biblioteca crypto para geraçao do OTP pois, math random pode gerar padrões reconheciveis

TypeScript
async storeOtp(email: string, otp: string): Promise<void> {
	await this.redisClient.set(`otp:${email}`, otp, "EX", this.OTP_EXPIRATION_TIME);
	await this.redisClient.set(`otp_retry_count:${email}`, 0, "EX", this.OTP_EXPIRATION_TIME);
}

a primeira funçao faz a definiçao do OTP value com o tempo de redefiniçao e a segunda funçao incializa a contagem de attempts

TypeScript
// a primeira funçao aplica o cooldown
async applyCooldown(email: string, cooldownTime: number): Promise<void>{
	const currentTime = Math.floor(Date.now() / 1000);
	await this.redisClient.set(`otp_cooldown:${email}`, (currentTime + cooldownTime).toString(), "EX",      cooldownTime);
}

// a segunda avalia de o usuario está em periodo de cooldown
async isOnCooldown(email: string){
	const currentTime = Math.floor(Date.now()/ 1000);
	const cooldownTimestamp = await this.redisClient.get(`otp_cooldown:${email}`);

if(cooldownTimestamp && currentTime < Number(cooldownTimestamp)) {
	const timeLeft = Number(cooldownTimestamp) - currentTime;
	const minutesLeft = Math.floor(timeLeft / 60);
	const secondsLeft = timeLeft % 60;
	
	throw new HttpException(
	 `OTP request is on cooldown, Please wait ${minutesLeft} minutes and ${secondsLeft} seconds.`,
	 HttpStatus.TOO_MANY_REQUESTS,
	)
}
}

funçao para gerar o OTP

TypeScript
async requestOTP(email: string, name?: string){ 
	await this.isOnCooldown(email);
	
	const otp = this.getRandomSixDigit().toString()
	
	const hashedOTP = await hash(otp, 10);
	
	await this.storeOtp(email, hashedOTP);
	
	await this.applyCooldown(email, this.SHORT_COOL_TIME);
	
	await this.mailService.sendOTP(email, name, otp);
	
	
	
}
TypeScript


async verifyOTP(email: string, otp: string){ 

		//cria um lock de chaves para impedir que dois usuario para que o usuario so faça uma autenticacao por vez
	const lockKey = `lock:otp:${email}`;
	const lockToken = randomUUID();
	
	const acquired = await this.redisClient.set(
	  lockKey,
	  lockToken,
	  'EX', 30,
	  'NX'
	);


	if (!acquired) {
	  throw new HttpException(
	    'OTP verification already in progress',
	    HttpStatus.CONFLICT
	  );
	}
	try{
	
	
		//aqui ele puxa do redis o otp que está atrelado ao email	
	const storedHashedOtp = await this.redisClient.get(`otp:${email}`);
	
	if(!storedHashedOtp){
	throw new HttpException(
				'invalid OTP', 
				HttpStatus.BAD_REQUEST
			);
	}
	
	//aqui ele verifica a quantidade de retry_counts desse email
	const retryCount = Number(await this.redisClient.get(`otp_retry_count:${email}`)) || 0;
	
	if(retryCount >= this.MAX_RETRY_COUNT){
			throw new HttpException(
				'Maximum retry attempts reached', 
				HttpStatus.FORBIDDEN
			);
			
		}
	
		
	//faz a comparaçao entre o que o usuario envio e o que tem no banco
	const isverified = await compare(otp, storedHashedOtp);
	
	//caso esteja errado ele faz um incremento na funçao de contagem de attempts
	if(!isverified) {
		await this.redisClient.incr(`otp_retry_count:${email}`);
		
		if(retryCount + 1 >= this.MAX_RETRY_COUNT){
			await this.applyCooldown(email, this.LONG_COOLDOWN_TIME);
			}
			
			throw new HttpException('invalid OTP', HttpStatus.FORBIDDEN);
	}
	//caso passe ele atualiza o status do cliente para verificado = true

	await this.db.update(users).set({isVerified: true}).where(eq(users.email, email));
	await this.redisClient.del(`otp:${email}`);
	await this.redisClient.del(`otp_retry_count:${email}`);

	}
	finally {
	  await this.redisClient.eval(
	    `if redis.call("GET", KEYS[1]) == ARGV[1] then
	       return redis.call("DEL", KEYS[1])
	     end
	     return 0`,
	    1,
	    lockKey,
	    lockToken
	  );
	}
}