npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nestjs-k8s-leader-election

v1.1.7

Published

Nestjs k8s leader election

Downloads

2,039

Readme

NestJS Kubernetes Leader Election

This NestJS module implements leader election for applications running on Kubernetes. It ensures that a particular task is only performed by one pod at a time in a cluster, which is crucial for high-availability and consistent operations.

Installation

npm install nestjs-k8s-leader-election

or with Yarn:

yarn add nestjs-k8s-leader-election

Usage

Import the LeaderElectionModule into the root AppModule and configure it:

// ... other imports ...
import { LeaderElectionModule } from 'nestjs-k8s-leader-election';

@Module({
  imports: [
    LeaderElectionModule.forRoot({
      // ... configuration options ...
    }),
    // ... other modules
  ],
  // ... controllers, providers
})
export class AppModule {}

Advanced Usage with Watch Feature

The service utilizes the Kubernetes watch feature to monitor lease objects for changes. This is particularly beneficial for systems that require immediate response to leadership changes and can greatly improve the reliability and fault tolerance of distributed systems.

When a lease is modified or deleted, the service responds in real-time, allowing for quick failover and ensuring that only one instance of the application assumes leadership at any given time. This makes the system well-suited for handling scale and high load, as leadership transitions are smooth and immediate.

Handling Events

The module emits events when leadership is acquired or lost. Use the @OnEvent decorator to handle these events:

// ... other imports ...
import { OnEvent } from '@nestjs/event-emitter';
import { LeaderElectedEvent, LeaderLostEvent } from 'nestjs-k8s-leader-election';

@Injectable()
export class TaskService {
  @OnEvent(LeaderElectedEvent)
  handleLeaderElected(event: { leaseName: string }) {
    // Logic when becoming the leader
  }

  @OnEvent(LeaderLostEvent)
  handleLeaderLost(event: leaseName: string) {
    // Logic when losing leadership
  }
}

Configuration Options

  • leaseName: Name of the lease resource.
  • namespace: Kubernetes namespace for the lease.
  • renewalInterval: Interval to attempt lease renewal (in milliseconds).
  • logAtLevel: Can log at either log or debug
  • awaitLeadership: Should the nestjs app await assuming leadership (or failing to) to load?

Kubernetes RBAC Configuration

To allow your application to manage leases, set up the appropriate RBAC configuration in Kubernetes. This involves creating a ServiceAccount, Role, and RoleBinding to grant the necessary permissions.

# ServiceAccount
apiVersion: v1
kind: ServiceAccount
metadata:
  name: your-service-account
  namespace: default

# Role
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  namespace: default
  name: lease-manager-role
rules:
- apiGroups: ["coordination.k8s.io"]
  resources: ["leases"]
  verbs: ["get", "watch", "list", "create", "update", "delete"]

# RoleBinding
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: lease-manager-rolebinding
  namespace: default
subjects:
- kind: ServiceAccount
  name: your-service-account
  namespace: default
roleRef:
  kind: Role
  name: lease-manager-role
  apiGroup: rbac.authorization.k8s.io

Then, reference the ServiceAccount in your pod's deployment configuration:

spec:
  template:
    spec:
      serviceAccountName: your-service-account
      # ... other specs ...

Contributing

Contributions to improve the module are welcome. Please submit your pull requests or issues as needed.

Sponsor

This project is sponsored and developed by Precise Finance, precisefinance.ai.

License

This project is licensed under the MIT License - see the LICENSE file for details.