0% found this document useful (0 votes)
3 views15 pages

Explained 1

The document outlines the architecture and technology stack of Mergyn, a platform that connects student developers with companies through coding challenges. It details the MERN stack (MongoDB, Express, React, Node.js) used for both frontend and backend development, along with authentication via Clerk and data management through Mongoose. Additionally, it describes the core workflows, database schema, and middleware functionalities essential for interview preparation related to the Mergyn platform.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

Explained 1

The document outlines the architecture and technology stack of Mergyn, a platform that connects student developers with companies through coding challenges. It details the MERN stack (MongoDB, Express, React, Node.js) used for both frontend and backend development, along with authentication via Clerk and data management through Mongoose. Additionally, it describes the core workflows, database schema, and middleware functionalities essential for interview preparation related to the Mergyn platform.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Mergyn Core Platform: Study

Guide & Interview Prep (TCS


Digital)
This document explains the architecture, tech stack, and internal
workflows of Mergyn, a platform connecting student developers with
companies through real-world coding challenges and open-source
contributions.

To keep your interview preparation focused and safe, all explanations


in this document are strictly mapped to the MERN stack (MongoDB,
Express, React, [Link]). Complex infrastructure (like PostgreSQL,
Prisma, Redis, and BullMQ queues) has been replaced in these
explanations with pure MERN solutions.

1. High-Level Architecture & Workflow

Mergyn follows a classic Client-Server (Three-Tier) Architecture


composed of:

1. Presentation Layer (Frontend): A web interface built with React


and [Link] where students view challenges/leaderboards and
companies manage submissions.
2. Application Layer (Backend API): A [Link] and Express REST
API that handles business logic, validates data, and performs
background tasks.
3. Database Layer: MongoDB (NoSQL) managed via Mongoose,
storing all application data (Users, Challenges, Submissions, and
the Reputation Ledger).
Core Workflow of the Application

+------------+ REST API Requests


| Frontend | ======================================>
| ([Link]) | <======================================
+------------+ JSON Web Tokens

1. Authentication: Users sign up or log in using GitHub OAuth via


Clerk. Once authenticated, Clerk provides a session token (JWT)
to the frontend, which is attached to the headers of all backend
API requests.
2. Challenge Creation: A company writes a coding challenge,
pointing to a public GitHub repository. This is stored in MongoDB.
3. Submission: A student accepts the challenge, works on it,
creates a pull request on GitHub, and submits the Pull Request
URL to Mergyn.
4. Automated Validation: The backend picks up the submission,
simulates a test runner to check if the URL format is valid, updates
the submission status in MongoDB (passed or failed), and logs
the event.
5. Ledger Approval: When the company accepts the submission,
the backend logs a contribution_merged event in an append-
only collection in MongoDB. This event is used to dynamically
calculate the student's "Cred" points for the leaderboard.

2. Technology Stack & Core Definitions

For your interview, you should be able to define and explain every part
of the stack. Here are bite-sized definitions:
Backend & Database (Node, Express, MongoDB)

• [Link]: An open-source, cross-platform JavaScript runtime


environment that allows developers to run JavaScript on the
server side. It is single-threaded and uses an event-driven, non-
blocking I/O model, making it highly lightweight and efficient.
• [Link]: A minimal and flexible [Link] web application
framework that provides a robust set of features for building web
and mobile applications (specifically handling HTTP routing,
request parameters, and middleware).
• MongoDB: A NoSQL, document-oriented database that stores
data in flexible, JSON-like documents (called BSON). It is highly
scalable and allows schemas to evolve dynamically.
• Mongoose: An Object Data Modeling (ODM) library for MongoDB
and [Link]. It manages relationships between data, provides
schema validation, and translates between objects in code and
documents in MongoDB.
• MongoDB Schema vs. Collection: A Collection is a grouping of
MongoDB documents (equivalent to a table in SQL). A Schema is
defined in Mongoose to structure the documents inside that
collection (defining fields, data types, validators, and default
values).
• REST API: Representational State Transfer. An architectural style
for designing networked applications. It relies on a stateless,
client-server protocol—almost always HTTP. It uses standard
HTTP methods:
○ GET: Retrieve data.
○ POST: Create new data.
○ PUT/PATCH: Update existing data.
○ DELETE: Remove data.
• JSON (JavaScript Object Notation): A lightweight data-
interchange format that is easy for humans to read and write, and
easy for machines to parse and generate. It is the primary format
used for communication between the Mergyn frontend and
backend.
• CORS (Cross-Origin Resource Sharing): A security mechanism
implemented by web browsers to restrict web pages from making
requests to a different domain than the one that served the web
page. We configure CORS in Express to allow requests from our
frontend domain (localhost:3000).

Frontend (React, [Link], Tailwind CSS)

• React: A popular frontend JavaScript library developed by Meta


for building user interfaces, specifically single-page applications. It
focuses on reusable components and uses a virtual DOM for fast
rendering.
• [Link] (App Router): A React framework that enables server-
side rendering (SSR), static site generation (SSG), and simplified
folder-based routing. The App Router optimizes rendering speed
by deciding which components run on the server versus the client.
• Tailwind CSS: A utility-first CSS framework that provides low-
level utility classes (e.g., flex, pt-4, text-center) directly in
the HTML/JSX code, enabling rapid UI styling without writing
custom CSS files.

Authentication & Security

• Clerk: A complete user authentication and management service. It


handles sign-up, sign-in, profile management, and OAuth (Social
logins like GitHub) out-of-the-box.
• JWT (JSON Web Token): A compact, URL-safe means of
representing claims to be transferred between two parties. The
frontend sends the Clerk JWT in the Authorization: Bearer
<token> header, which the backend decodes to identify the user
(clerkId) and verify their identity.

3. Database Schema Design (Pure MongoDB)

In this simplified model, all data resides in MongoDB collections. We


define four main collections:
1. Users Collection (users)

Stores information about students, companies, and admin accounts.

• clerkId (String, Indexed, Unique): The unique identifier


generated by Clerk. This binds the database user to the
authenticated user.
• role (String): Can be 'student', 'company', or 'admin'.
• name (String): Full name of the user.
• email (String): Email address.
• githubUsername (String, Optional): Linked GitHub account
username.
• companyName (String, Optional): If the user is a company, stores
their organization name.
• university (String, Optional): If the user is a student, stores
their college.
• verified (Boolean): Indicates whether a company account has
been verified by an admin.

2. Challenges Collection (challenges)

Stores the coding tasks posted by companies.

• title (String): Name of the challenge.


• description (String): Details of what needs to be solved.
• repoUrl (String): The GitHub repository URL associated with the
challenge.
• companyId (String): The clerkId of the company user who
created this challenge.
• difficulty (String): 'beginner', 'intermediate', or
'advanced'.
• status (String): 'draft' (pending admin review), 'open'
(active and solveable), or 'closed'.

3. Submissions Collection (submissions)

Stores student submissions for challenges.


• challengeId (ObjectId): Reference to the associated document
in the challenges collection.
• studentId (String): The clerkId of the student who submitted
the code.
• patchUrl (String): The link to the GitHub Pull Request or patch.
• status (String): 'pending', 'accepted', or 'rejected'.
• sandboxStatus (String): Results of validation—'passed' or
'failed'.

4. Ledger Events Collection (ledger_events)

An append-only log recording contribution milestones for trust scores.

• id (ObjectId/String): Unique ID of the event.


• contributorId (String): The clerkId of the student.
• eventType (String): Set to 'contribution_merged'.
• metadata (Object): Custom payload containing the associated
challengeId and submissionId.
• createdAt (Date): Timestamp when the contribution was
finalized.

4. Backend Implementation Details

How Routing & Middleware Work together

In Express, middleware functions execute sequentially before the final


route handler. In Mergyn, we protect endpoints using two custom
middleware functions:

1. requireClerkAuth Middleware:

• Reads the Authorization header from the incoming


request.
• Extracts the token (Bearer JWT).
• Uses Clerk's SDK to verify the token signature. If invalid,
returns a 401 Unauthorized response.
• If valid, extracts the Clerk user ID and queries MongoDB's
users collection to check the user's role.
• Attaches the user object { userId, role } to the
[Link] object and calls next().

2. requireRole Middleware:

• Executes after authentication middleware.


• Takes allowed roles as arguments (e.g.,
requireRole('company', 'admin')).
• Checks if [Link] is in the allowed list. If not,
returns a 403 Forbidden response.
• If allowed, calls next() to proceed to the route handler.

Background Task Simulation (Simplified Verification)

To keep the backend simple and eliminate Redis, background validation


is handled using [Link] event loops:

• When a student posts a submission (POST /submissions), the


API creates a pending submission record in MongoDB.
• Instead of queuing a job to an external worker, the Express route
handler fires an asynchronous JavaScript function
(setImmediate or setTimeout with a duration of 2 seconds to
simulate sandbox latency) to analyze the submission.
• This async function:
1. Regex-validates the submitted URL structure to verify it
matches a valid GitHub PR format.
2. Updates the sandboxStatus in MongoDB to 'passed' or
'failed'.
3. Triggers a database write to save the state.
• The API immediately sends a 201 Created response back to the
client without blocking the server while the async function runs.

Dynamic Ledger Scoring (Dynamic Aggregation)

Instead of storing a student's total points as a single database field


(which can easily be tampered with or desynchronized), we calculate
scores dynamically:

• Every time a student's solution is approved by a company, a new


document is inserted into the ledger_events collection.
• To compute a student's score or display the Leaderboard, the
Express backend runs a MongoDB Aggregation Pipeline:

// Leaderboard Aggregation Example


[Link]([
{ $match: { eventType: 'contribution_merged' } }, /
{ $group: { _id: "$contributorId", totalCred: { $su
{ $sort: { totalCred: -1 } }, // 3. Sort by count i
{ $limit: 20 } // 4. Take the top 20
])

• This ensures that the score is always an immutable audit trail


derived directly from successful merges, satisfying the "Append-
Only" architecture requirement.

5. Deployment Architecture

To deployment, we use a simple structure:

• Database: MongoDB Atlas (fully managed cloud database).


• Backend API: Hosted on Render as a web service. We supply it
with environment variables (MONGODB_URI,
CLERK_SECRET_KEY) using Render's dashboard.
• Frontend: Hosted on Vercel with automatic deployment on git
pushes.

6. Interview Q&A (Mergyn Core Platform)


These questions are structured to mirror standard TCS Digital interview
questions.

Q1: What is the main idea behind your project, Mergyn?

Answer: Mergyn is a platform connecting developers (students) with


companies through real-world coding challenges. Instead of sharing
generic resumes, students solve coding challenges posted by
companies, submit pull requests, and earn verified points (Cred). It acts
as a talent pipeline verified by actual code.

Q2: What is the tech stack of the Mergyn project?

Answer: The project is built on the MERN Stack (MongoDB, Express,


React, and [Link]) in a TypeScript monorepo. We use [Link] on the
frontend, Express on the backend, MongoDB with Mongoose on the
database layer, and Clerk for secure authentication.

Q3: Why did you choose MongoDB over a relational


database like SQL?

Answer: We chose MongoDB because our application works with


objects whose structures can change, such as challenge descriptions,
student profiles, and rich metadata for submissions. MongoDB's NoSQL
document model allows us to iterate rapidly without needing complex
table migrations or expensive JOIN operations.

Q4: Explain the difference between [Link] and


[Link].

Answer: [Link] is a runtime environment that allows us to run


JavaScript outside the browser, on our backend server. [Link] is a
web application framework built on top of [Link] that simplifies handling
HTTP requests, routing, middleware integration, and designing RESTful
APIs.
Q5: How is user authentication managed in Mergyn?

Answer: User authentication is handled by Clerk. When a user logs in


(using GitHub OAuth), Clerk generates a secure JSON Web Token
(JWT). The frontend intercepts this token and sends it in the headers of
all API calls. The backend intercepts this header, decodes the JWT
using Clerk's SDK, and verifies the user's signature.

Q6: What is a Middleware in Express? Can you name a


middleware used in your project?

Answer: Middleware functions are functions that have access to the


request object (req), the response object (res), and the next
middleware function in the application’s request-response cycle. In our
project, we use requireClerkAuth to parse user session tokens and
check authentication, and a custom role-based middleware
(requireRole) to restrict administrative routes to admins and
companies.

Q7: What is CORS, and how does your backend address


it?

Answer: CORS stands for Cross-Origin Resource Sharing. It is a


security feature enforced by browsers that blocks web applications
hosted on one origin (e.g., [Link] from requesting
resources from a different origin (e.g., [Link] We
resolved this in our Express backend by using the cors middleware,
explicitly listing our frontend URL in the allowed origins.

Q8: What is Mongoose? What is its role in your project?

Answer: Mongoose is an Object Data Modeling (ODM) library for


MongoDB and [Link]. In Mergyn, Mongoose acts as a schema-
validation layer. It ensures that any document written to our MongoDB
collections (like a User, Challenge, or Submission) conforms to our
predefined data types and structures.
Q9: How do you handle schema validation in your
Express backend?

Answer: We implement validation at two levels. On the database layer,


Mongoose enforces rules (e.g., checking if a field is required or matches
an enum). On the environment level, we use Zod schema parser during
startup to ensure all system credentials (like MongoDB URI or Clerk API
Keys) are loaded correctly.

Q10: How do you perform database indexing in


MongoDB? Why is it important?

Answer: Indexing improves the performance of read queries in


MongoDB by preventing full collection scans. In our schemas, we create
indices on search keys. For example, in the users schema, we index
clerkId to query profile details quickly. In the challenges schema,
we use a compound index on { companyId: 1, status: 1 } to
quickly display a company's review queue.

Q11: Explain how you model relations in MongoDB, for


example, linking a Submission to a Challenge.

Answer: In our Mongoose Submission schema, we define the


challengeId field with a type of [Link] and set
ref: 'Challenge'. When we retrieve submissions, we can query this
relation using Mongoose's .find() and attach challenge details by
querying the referenced collection.

Q12: How do you implement roles and access control in


your application?

Answer: We store a user's role (student, company, or admin) in the


users collection in MongoDB. When a request is authenticated in our
requireClerkAuth middleware, we look up the user's role from
MongoDB and attach it to [Link]. Then, the requireRole
middleware checks if that role is permitted to access the requested route
(e.g., only a company can POST a challenge).

Q13: What are the HTTP status codes you return in the
API? Can you give examples?

Answer: We use standard REST status codes:

• 200 OK: Successful data fetch (fetching challenges list).


• 201 Created: Successful creation (submitting a new patch).
• 400 Bad Request: Malformed payload (missing fields in body).
• 401 Unauthorized: Missing or invalid auth token.
• 403 Forbidden: Authenticated user lacks permission (student
accessing company review queue).
• 404 Not Found: Resource does not exist (invalid challenge ID).
• 500 Internal Server Error: Server-side errors.

Q14: How does the dynamic leaderboard scoring work?

Answer: When a submission is approved, we insert an event document


into the ledger_events collection. To fetch the leaderboard, the
backend runs an aggregation pipeline matching only
contribution_merged events, grouping them by contributorId,
counting the number of records, sorting them in descending order, and
fetching user profiles for the top 20.

Q15: Why is the ledger system "append-only"? How does


it prevent cheating?

Answer: The ledger is designed to be append-only because users can


easily manipulate a numeric score column (e.g., totalCred = 100).
By calculating points dynamically from individual event rows, any
malicious change or deletion of user records is prevented. The total
score is computed mathematically from the history of approved
contributions.
Q16: How do you handle long-running operations like
checking patch syntax on submission?

Answer: When a student posts a submission, we immediately write the


submission as pending to MongoDB and send a 201 Created HTTP
response back to the client. In the background, the server runs a non-
blocking asynchronous function to perform checks (URL checks,
verification logic). Once completed, it updates the record's status in
MongoDB.

Q17: What is the event loop in [Link], and how does it


help your server remain responsive?

Answer: The event loop is what allows [Link] to perform non-blocking


I/O operations despite JavaScript being single-threaded. When tasks like
reading files or querying MongoDB are executed, Node offloads them to
the system kernel or a worker pool. Once complete, the callback is
queued to the event loop, letting the main thread handle incoming
requests.

Q18: What is a Monorepo? How is Mergyn organized?

Answer: A monorepo is a version control strategy where code for


multiple projects (in our case, the [Link] web application and the
Express backend API) is stored in the same repository. We manage this
monorepo using Turborepo, which shares TypeScript configurations
and models easily.

Q19: Explain the difference between client-side rendering


(CSR) and server-side rendering (SSR) in [Link].

Answer:

• CSR: The server sends a bare-bones HTML shell and a large


bundle of JavaScript. The browser downloads the JS and
generates the UI. It's highly interactive but slower for initial page
load.
• SSR: The server executes the React code, renders the HTML with
populated data, and sends the finished page to the browser. This
offers a faster initial paint and better SEO search indexing.

Q20: What is the role of the Clerk synchronization route


(POST /auth/sync-user)?

Answer: When a user registers through Clerk's UI, the user metadata is
created on Clerk's servers. To store this information in our local
MongoDB collection (to handle search queries and join relations), we
call /auth/sync-user upon onboarding. It extracts the Clerk profile
information and upserts it into our MongoDB users collection.

Q21: What is an "upsert" operation in MongoDB?

Answer: An upsert is a database operation that updates a document if it


matches a query condition, or creates a new document with the provided
data if no match is found. In Mongoose, we implement this using {
upsert: true } in findOneAndUpdate().

Q22: What is the purpose of Zod in your project?

Answer: Zod is a TypeScript-first schema declaration and validation


library. We use Zod to validate the environment variables
([Link]) on server boot. If a developer forgets to set vital
credentials (like MONGODB_URI or CLERK_SECRET_KEY), Zod fails
validation and crashes the server immediately, preventing runtime
failures.

Q23: How do you protect your API routes from abusive


traffic?

Answer: We protect crucial routes (like AI chat endpoints) using a


simple in-memory rate limiter middleware. The middleware tracks the
request count per userId in a JavaScript Map. If a user exceeds the
threshold (e.g., 30 requests per hour), the middleware blocks the call
and returns an HTTP 429 Too Many Requests code.

Q24: How would you scale this MERN architecture if


traffic increased?

Answer: To scale this setup, we would:

1. Add a load balancer (like NGINX) in front of multiple instances of


our Node/Express server.
2. Enable MongoDB horizontal scaling (sharding) to distribute data
across multiple database clusters.
3. Implement a caching layer (like Redis) to store frequently retrieved
static values (such as challenge lists).

Q25: How do you verify that GitHub Webhooks are


secure?

Answer: GitHub sends a cryptographic signature in the request headers


(x-hub-signature-256) representing an HMAC digest of the request
body using a shared secret key. On the backend, we calculate the
HMAC hash of the raw request payload using our local secret and use
[Link] to compare it to the header, rejecting fake
requests.

You might also like