
Real Interview Questions for the Software Engineer at Totvs
NewInterview Q&A
Q&A-1Can you describe your experience with Node.js, TypeScript, or React in previous projects?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I used the three together in a production order and inventory system. Node.js 20 with TypeScript 5 on the backend, React 18 on the frontend, PostgreSQL behind it. The backend exposed a REST API for orders and stock movements, the React app was the operator console for warehouse staff. I owned the API contract and the data layer, and built the screens that created and tracked orders.
The reason for TypeScript across the boundary was practical. A type error at compile time in the frontend is cheaper than a 422 in production. I kept one shared package for request and response types, and validated every request at runtime because types disappear over the wire.
// shared/orders.ts, TypeScript 5.5, strict mode
export type OrderStatus = "draft" | "confirmed" | "shipped" | "cancelled";
export interface CreateOrderRequest {
customerId: string;
lines: Array<{ sku: string; qty: number }>;
idempotencyKey: string;
}
const TRANSITIONS: Record<OrderStatus, OrderStatus[]> = {
draft: ["confirmed", "cancelled"],
confirmed: ["shipped", "cancelled"],
shipped: [],
cancelled: [],
};
export function canTransition(from: OrderStatus, to: OrderStatus): boolean {
return TRANSITIONS[from].includes(to);
}The server checked canTransition before any write, so an illegal jump from shipped to cancelled failed with 409 instead of corrupting state. The React side used the same type, so the cancel button was disabled before the request was ever sent.
Node.js, and where it hurt
Node is single threaded per process for JavaScript, so I treated CPU work as the enemy. JSON parsing of a 5 MB import file blocked the event loop for about 400 ms in our first version, and p99 latency for unrelated requests went from 40 ms to over 300 ms. We moved parsing to a worker thread and chunked the import into batches of 500 rows. Rule of thumb I now use: any handler that can run longer than 50 ms of CPU gets measured, and anything over that goes off the request path.
I/O was the opposite case. With 20 database connections in the pool and 200 concurrent operators, the pool saturated and requests queued. Adding connections did not help because Postgres was the bottleneck. We capped concurrency per route, added a 2 s statement timeout, and returned 503 with Retry-After instead of letting requests pile up until the load balancer timed out.
React, and where it hurt
The order list rendered 2,000 rows and re-rendered on every stock update, which arrived over a websocket every second or so. Profiling showed the bottleneck was not rendering, it was recreating row components and inline callbacks. We virtualised the list, memoised rows with React.memo, and split the websocket updates so only the affected row received new props. Frame time dropped from 90 ms to under 16 ms on a mid range laptop, which is the difference between a usable console and one operators complained about.
| Failure mode | Symptom | Fix that worked |
|---|---|---|
| Unhandled promise rejection in a route handler | Process exited, health check failed, all in flight requests dropped | Central error middleware, process.on("unhandledRejection") wired to alerting, tests that force a downstream timeout |
| Type drift between frontend and backend | Frontend sent qty as string, server returned 422, user saw a generic error | Shared types plus runtime schema validation on both sides, contract tests in CI |
| Stale state after a concurrent update | Two operators edited the same order, second save silently overwrote the first | ETag and If-Match on PATCH, 409 on mismatch, UI showed the current version |
| Large bundle from importing a whole library | Initial load over 2 MB, slow on warehouse tablets | Route level code splitting, import from the specific module path, bundle budget checked in CI |
What I would not use it for
Node is a poor fit for CPU heavy work such as image processing or large report generation in process. We offloaded report generation to a separate worker service that wrote to object storage and notified the frontend when the file was ready. React is also a poor fit when the interface needs to update at 60 Hz, such as a live chart of sensor data. We rendered that on a canvas instead of the DOM.
If I joined a team running this stack today, I would start by checking three things: whether strict TypeScript is actually enforced, whether the API has idempotency keys on creates, and whether there is a load test that shows what happens when the database pool saturates. Those three tell me more about the codebase than any architecture diagram.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-2How do you handle state management in complex front-end applications?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I split state by lifetime and source before I pick a tool. Server state, meaning orders, customers, stock and prices that another user can change, lives in a query cache keyed by the request. UI state, meaning the open drawer, the selected grid row, the current branch filter, lives close to the component or in a small client store. Form state lives in the form itself until submit. Mixing those three in one global store is where complex ERP screens break.
For a TOTVS order entry screen that means the order header and its items come from the API through TanStack Query, the branch and warehouse context come from the authenticated session, and only ephemeral things like which line is being edited sit in Zustand. Totals, tax and discount are derived with selectors from the lines, never stored as a second copy that can drift.
// TypeScript, React 18, TanStack Query 5, Zustand 5
const useUi = create<UiState>((set) => ({
branchId: 'filial-01',
editingLineId: null,
setEditingLine: (id) => set({ editingLineId: id }),
}));
function useOrder(orderId: string) {
const branchId = useUi((s) => s.branchId);
return useQuery({
queryKey: ['order', branchId, orderId],
queryFn: () => api.getOrder(branchId, orderId),
staleTime: 30_000,
});
}
const totals = useMemo(
() => computeTotals(order?.items ?? []),
[order?.items],
);The branchId in the query key matters in a multi-branch ERP. Without it, switching filial reuses the previous branch's cached order for up to the stale window and the screen shows prices and stock for the wrong branch. With it, each branch has its own cache entry and invalidation is scoped.
| State kind | Where it lives | Example in order entry | Update rule |
|---|---|---|---|
| Server state | Query cache | Order, customer, item price table | Invalidate on mutation, refetch on focus |
| Session state | Auth/session context | User, branch, permissions | Set at login, cleared at logout |
| UI state | Local state or small store | Open tab, selected row, drawer | Local first, lift only when shared |
| Form state | Form library or local state | Unsaved header fields | Validate on change, commit on submit |
| URL state | Router params/search | ?status=open&branch=01 | Shareable, restorable on refresh |
Why this shape holds up
A 40-field form typed into a single global store re-renders every subscriber on each keystroke. With selectors, the header panel subscribes to header fields and the totals panel subscribes to the computed total, so typing in a description field does not re-render an 800-row items grid. In practice I check that with the React profiler or Angular DevTools and look for render counts, not intuition.
Two failure modes come up repeatedly. The first is a race on save. A user edits line 3, the save takes 900 ms, and meanwhile a stock check returns and overwrites the line. I guard mutations with the server version or ETag returned by the last read, and on a 409 I refetch and show the conflict instead of silently overwriting. The second is optimistic updates without rollback. I apply the optimistic line change, and if the request fails I restore the previous cache snapshot and surface the error on that line, because a silently reverted total looks like data loss to an operator.
Reference data needs a different staleTime from transactional data. A product price table can be cached for five minutes, an order being edited by another user cannot. I set staleTime per query, add refetchOnWindowFocus for the order being edited, and keep the query devtools open during testing to confirm invalidation actually fires after a mutation. If a mutation succeeds but the list still shows the old status, the usual cause is a missing invalidation for the list key, and that is a test I write before the screen ships.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-3What are the primary differences between REST and GraphQL in your experience?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
REST models the API around resources and HTTP semantics. GraphQL models it around a typed schema and lets the client name the fields it wants in one query. I pick based on who consumes the API, how stable the contract needs to be, and whether caching at the HTTP layer matters.
In an ERP context like Totvs, where the same order data feeds a web back office, a mobile app for field sales, and partner integrations that live for years, that choice is rarely about preference. It is about contract lifetime and query shape.
| Dimension | REST | GraphQL |
|---|---|---|
| Address | Many URLs, one per resource: GET /orders/{id} | One endpoint, usually POST /graphql, fields chosen in the body |
| Contract | Resource shape defined by the server, versioned by URL or media type | Schema defined in SDL, versioned by deprecating fields |
| Fetching | Server decides the payload, client may overfetch or need follow-up calls | Client decides fields, server resolves the graph |
| Caching | HTTP cache, CDN, ETag and Cache-Control work per URL | Usually bypasses HTTP cache, needs persisted queries or a cache keyed by query hash plus variables |
| Errors | HTTP status per resource | 200 with an errors array, partial data possible |
| Tooling | OpenAPI, easy to generate clients and mocks | Codegen from schema, introspection, query cost analysis |
Same request, both styles
A sales screen needs order 42, its customer name, and only the item descriptions and quantities.
GET /orders/42?fields=customer.name,items.description,items.qtyquery OrderDetail($id: ID!) {
order(id: $id) {
id
customer { name }
items { description qty }
}
}The REST version depends on the server supporting that fields parameter. Without it, the client receives the full order representation, including pricing history and internal status fields it never displays. The GraphQL version states the need explicitly, and the schema rejects a field that does not exist before the resolver runs.
Where each one breaks
REST fails on graph-shaped screens. A dashboard that needs orders, customers, products and stock levels can turn into a waterfall: one call for the order list, then one per customer, then one per product. With 50 orders on a page, that is 101 requests if the client is naive, and the latency adds up even when each call is fast. The fix is usually an aggregate endpoint such as GET /order-dashboard, which then becomes a second, overlapping contract to maintain.
GraphQL moves that problem into the resolver layer. A query that looks like one request can fan out badly:
| Step | REST waterfall | GraphQL resolver trace |
|---|---|---|
| 1 | GET /orders?limit=50 returns 50 ids | orders(limit: 50) resolves 50 order rows |
| 2 | 50 calls to GET /customers/{id} | 50 calls to customer resolver unless batched |
| 3 | 50 calls to GET /items?order_id=... | 50 calls to items resolver unless batched |
| Total | 101 HTTP requests | 1 HTTP request, 151 database queries without batching |
That is why I would never ship GraphQL without DataLoader-style batching, a query depth and cost limit, and persisted queries for the mobile client. Without those, a single crafted query with nested items { product { supplier { ... } } } can saturate the database while the HTTP metrics still look like one cheap POST.
How I decide in practice
For public or partner APIs, and for anything that needs CDN caching, webhooks, or file uploads, I stay with REST. The contract is boring in a good way, and a partner can implement it from an OpenAPI document without learning a query language.
For internal product surfaces with several clients asking different subsets of the same graph, GraphQL earns its cost. One schema becomes the shared vocabulary between web, mobile and the back office, and field deprecation lets us evolve it without a /v2 fork.
The mistake I see most often is treating GraphQL as REST with flexible fields. It is a different operating model: you trade HTTP caching and simple versioning for client-driven selection, and you have to budget for resolver performance, query governance and cache design up front. If the team will not staff that, REST with a few well-chosen aggregate endpoints is the safer call.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-4How do you approach debugging a performance bottleneck in a production environment?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I do not start with a profiler. I start by pinning down the symptom in numbers, because "slow" in an ERP system can mean a lock on a fiscal table, a full thread pool, or one customer with 40 million rows. I ask which endpoint, which tenant or company, p50 and p99 before and after, when it started, and what changed in that window: deploy, data volume, a new index, a batch job, a partner integration. If I cannot state the regression as a delta, I do not have a bottleneck yet, I have a complaint.
Then I split the latency before I open any code. For a request I want the breakdown across client wait, load balancer, application CPU, database, and downstream calls. That tells me whether to look at SQL, at a lock, or at my own service. Only then do I profile the hot path, reproduce it with production-like data, and fix the mechanism, not the symptom.
Quantify and split
In a Totvs-style environment, with Java services in front of Oracle or PostgreSQL and large transactional tables for orders, invoices, and inventory, the first split is usually between database time and application time. Distributed traces from OpenTelemetry or the APM already in place give me span duration by service. I check three things in parallel: error rate and throughput (did traffic double?), saturation (thread pool, connection pool, CPU, disk wait), and latency by dependency.
Little's Law makes queueing visible before I look at code. Hypothetical but typical figures from an incident: 120 requests per second, p99 latency up from 180 ms to 2.8 s. Concurrency in the service is roughly throughput times latency, so 120 x 2.8 = 336 requests in flight against a pool of 40 threads. The pool saturates, requests queue, p99 climbs further, and the database looks guilty when it is mostly waiting for a thread. That arithmetic changes the investigation from "tune the query" to "find what holds a thread for seconds."
| Signal | What I check | What it rules in or out |
|---|---|---|
| --- | --- | --- |
| Trace spans | DB span vs HTTP span vs downstream call | Slow SQL, slow code, or slow dependency |
| Pool metrics | Active threads, queue depth, connection wait time | Queueing inside the service |
| DB stats | pg_stat_statements or AWR top SQL by total time | One query, many queries, or lock waits |
| Host metrics | CPU, iowait, memory, GC pause | Contention outside the application |
Find the hot path
For the database side I rank by total time, not by single execution time. A query that runs 50,000 times a day at 40 ms costs more than one that runs twice at 2 s.
-- PostgreSQL, checked against pg_stat_statements
SELECT substring(query, 1, 80) AS query,
calls,
round(mean_exec_time::numeric, 1) AS mean_ms,
round(total_exec_time::numeric, 0) AS total_ms,
rows
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;Then I run EXPLAIN (ANALYZE, BUFFERS) on the exact statement with production parameters, because a plan that is fine for company 1 can be a sequential scan for company 87 with a different data distribution. On the application side I capture a short profile from a live instance, for example with async-profiler on a Java service:
# 60 s wall-clock profile, collapsed stacks
java -jar async-profiler.jar -e wall -d 60 -f /tmp/wall.svg <pid>Wall-clock matters here. CPU profiles miss time spent waiting on a lock, a socket, or a connection pool, which is exactly where ERP bottlenecks hide. I compare the profile against the trace spans so I am not optimising a method that accounts for 2% of the request.
Prove it before fixing, and do not break correctness
I reproduce with the same volume and the same tenant data shape, ideally a masked production snapshot, and I measure before and after on the same machine. A fix that only helps on my laptop with 10,000 rows proves nothing for a table with 80 million rows. I also check the failure modes that a performance fix can create. Adding an index speeds a read and slows every write that maintains it, and can change a query plan for other tenants. Caching an order total speeds reads and risks serving a stale fiscal value. Batching database calls cuts round trips and can turn a partial failure into a transaction that is harder to retry. I state which of those I am accepting and how I will detect it: write latency on the affected table, cache hit rate and invalidation lag, batch error rate.
I ship behind a flag or a canary for one company or one region first, watch p50, p99, pool saturation, and error rate for at least one full business cycle, and keep the rollback ready. If p99 does not move, the bottleneck was elsewhere and I say so. That discipline is what separates debugging from tuning by anecdote.
Follow-ups I expect
If the interviewer pushes on locks, I look at pg_locks or Oracle v$session for blocking sessions and the transaction that holds the row, often a long-running batch or an uncommitted fiscal emission. If they push on the JVM, I check GC pause and heap after the wall-clock profile, because a service can be slow from allocation pressure rather than from any single method. The method stays the same: quantify, split, profile the hot path, reproduce, then fix with a guardrail.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-5Can you explain your experience with cloud services and how you deploy your applications?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I have run services on AWS, mostly in sa-east-1, and I deploy them as container images through a pipeline that is boring on purpose. Build, test, scan, push the image, apply infrastructure with Terraform, then roll the service out with health-gated rolling deploys and an automatic rollback. The reason I keep that shape is the workload I know best: multi-tenant business systems, where a bad deploy does not just break a page, it blocks invoicing, stock moves or payroll for a customer.
At Totvs scale that means three constraints I design around from the start. Tenants share the platform but not the data, so every service needs a tenant identifier enforced in code and in the database, not just in the UI. Some customers still run on premises or in a private cloud, so the same artifact has to run in AWS and on a customer site without a fork. And data stays in Brazil for latency and for LGPD, so region choice is a product decision, not a default.
What I actually use, and why
Compute is ECS Fargate for most services. I do not need to patch or tune a node, and scaling is per service, which matters when an ERP module like fiscal document emission spikes at month end while a reporting service stays flat. I reach for EKS when a workload needs custom scheduling, GPU nodes or a stateful operator, and I accept the extra operational cost only then.
For data I keep the split explicit. RDS Postgres for transactional records, with Multi-AZ in the same region and automated backups tested by a restore drill, not assumed. S3 for files and exports, with versioning and a bucket policy that denies non-TLS access. SQS for work that can wait, such as generating a large report or posting an event to another module, because a queue absorbs a burst that would otherwise time out an HTTP request. ElastiCache only when I can name the hit rate it buys. A cache that saves 30 ms on a read called 200 times a day is complexity without a payoff.
Infrastructure is Terraform, one state per environment, with remote state in S3 and locking in DynamoDB. Secrets live in Secrets Manager or SSM Parameter Store, injected at task start, never baked into the image. Every environment gets the same modules, so dev, staging and production differ by variables like instance size and replica count, not by hand edits in a console.
How a deploy runs
A typical release is a GitHub Actions workflow. It builds the image, runs tests, scans the image for critical vulnerabilities, pushes it tagged with the commit SHA, then runs terraform plan on the pull request. After merge, the pipeline applies Terraform and updates the ECS service. ECS starts new tasks, waits for the health check on /healthz to pass, shifts traffic only when the new tasks are healthy, and drains the old ones. If error rate or p99 latency breaches the threshold in the first 10 minutes, the pipeline rolls back to the previous task definition. Database changes go out separately as expand-and-contract migrations: add the new column, deploy code that writes both, backfill, then drop the old column in a later release. That ordering is what lets a rollback stay safe.
| Choice | When I use it | Cost I accept |
|---|---|---|
| ECS Fargate rolling | Standard stateless service | Less control over the node, per-task pricing |
| EKS | Custom scheduling, GPU, operators | Node upgrades and cluster versioning are mine to run |
| Blue-green with ALB target groups | Risky change, need instant rollback | Double capacity during the switch |
| Canary by tenant or percentage | High blast radius, fiscal or payment flow | Slower rollout, needs traffic splitting and per-cohort metrics |
Failure modes I have hit and how I detect them
A migration that locks a hot table. The deploy looked fine, then p99 on the orders service went from 120 ms to over 2 s because a backfill held a lock. Detection was a lock wait alert plus the latency SLO. Fix was to move the backfill to a batched job and add the index concurrently.
Config drift between environments. Staging passed because a queue existed there by hand. Production failed on first deploy. Detection was the Terraform plan showing a missing resource. Fix was deleting console-created resources and importing them into Terraform so the pipeline owns them.
A rollback that was not a rollback. The image went back, but a schema change had already dropped a column, so the old code crashed on startup. Detection was the health check failing on the rolled-back tasks. Fix was the expand-and-contract rule above, plus a deploy check that runs the previous image against the current schema in staging before production.
An AZ-level slowdown. One availability zone degraded, and because tasks were spread evenly, half the fleet slowed. Detection was per-AZ latency dashboards. Fix was spreading tasks across at least two AZs with minHealthyCapacity at 100%, and keeping enough headroom that losing one AZ does not saturate the rest. As a rule of thumb I size for peak load on two thirds of capacity, so a single AZ loss is a capacity event, not an outage.
If you ask me what I would not do: I would not deploy by hand, I would not share one database credential across services, and I would not put tenant data in a region chosen for price alone. Those three choices are hard to undo once customers are on the platform.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-6Walk me through your approach to solving an algorithmic challenge.
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I run the same loop on every algorithmic problem, and I say it out loud so the interviewer can redirect me early. First, I restate the problem in my own words and pin down the inputs, outputs, and constraints. Second, I write a brute force solution that is obviously correct. Third, I look for the bottleneck in that solution and optimize only that part. Fourth, I test edge cases and state the complexity before I code the final version.
That order matters. Jumping to the clever trick first usually produces code that passes the happy path and fails on an empty input or a duplicate. A correct brute force gives me a reference to check the optimized version against.
Walking through a concrete example
Take a problem I have solved in interviews: merge overlapping intervals, for example delivery windows or appointment slots in an ERP scheduling screen. Input is a list of [start, end] pairs, output is the merged list.
Step 1, clarify. I ask: can intervals touch, so [1,3] and [3,5] merge to [1,5]? Can the input be unsorted? Can it be empty? Are start and end guaranteed valid? Those answers change the code, so I do not guess them.
Step 2, brute force. Compare every pair, merge if they overlap, repeat until nothing changes. That is O(n^2) comparisons. For n = 100,000 intervals, that is roughly 10^10 comparisons, which will not finish in a 2 second limit. The bottleneck is not merging, it is the repeated scanning.
Step 3, optimize. Sorting by start makes overlaps adjacent. One linear pass then merges everything. Sorting dominates, so O(n log n) time and O(n) space for the output.
# Python 3.12
def merge_intervals(intervals):
if not intervals:
return []
intervals = sorted(intervals, key=lambda x: x[0])
merged = [intervals[0]]
for start, end in intervals[1:]:
last_start, last_end = merged[-1]
if start <= last_end: # overlaps or touches the previous interval
merged[-1] = [last_start, max(last_end, end)]
else:
merged.append([start, end])
return mergedWorked trace for [[1,3],[2,6],[8,10],[15,18]]:
| Step | Current interval | Last merged | Decision | Merged so far |
|---|---|---|---|---|
| 1 | [1,3] | none | seed | [[1,3]] |
| 2 | [2,6] | [1,3] | 2 <= 3, merge to [1,6] | [[1,6]] |
| 3 | [8,10] | [1,6] | 8 > 6, append | [[1,6],[8,10]] |
| 4 | [15,18] | [8,10] | 15 > 10, append | [[1,6],[8,10],[15,18]] |
Step 4, verify. I run the brute force and the sorted version on small random inputs and compare outputs. Then I name the edge cases explicitly: empty list returns [], a single interval returns unchanged, fully nested intervals like [1,10],[2,3] collapse to [1,10] because of the max(last_end, end) line, and unsorted input is handled by the sort.
| Approach | Time | Space | When I would use it |
|---|---|---|---|
| Brute force pair comparison | O(n^2) | O(n) | n under a few hundred, or as a correctness oracle |
| Sort then single pass | O(n log n) | O(n) | General case, intervals can be reordered |
| Hash map or set trick | O(n) average | O(n) | Only when the problem has a fixed key, not ranges |
Failure modes I watch for
Off by one on the overlap test (< versus <=) is the classic bug here, which is why I clarify the touching case up front instead of deciding in code. Mutating the caller's list during sort is another one, so I sort a copy. In languages with fixed width integers, adding or subtracting timestamps can overflow, so I check the range of the inputs before doing arithmetic on them. If the interviewer changes a constraint mid discussion, for example intervals arrive already sorted, I drop the sort and say the complexity becomes O(n), rather than defending the earlier version.
I close by stating the final complexity and asking whether they want the follow up, such as streaming intervals that cannot all fit in memory. That signals I can extend the solution instead of stopping at the first version that passes.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-7How would you design a simple feature, such as a user authentication flow, considering security best practices?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I would build registration, login, email verification, password reset, and optional TOTP MFA as separate endpoints, with passwords hashed using Argon2id, sessions in secure HttpOnly cookies, and short-lived access tokens only where an API needs them. Every query is scoped to the authenticated tenant, because at Totvs a user belongs to a company tenant in an ERP context and cross-tenant access is the failure that matters most. I would assume TLS everywhere, LGPD applies to personal data, and the client is a browser plus a mobile app, so the design has to work for both.
Registration and login
Registration takes email, password, tenant identifier from the invitation or signup flow, and LGPD consent. The server, not the client, decides the tenant for later requests. Password policy: minimum 12 characters, check against a breached password list, no forced periodic rotation. Hash with Argon2id at OWASP parameters (memory 64 MiB, iterations 3, parallelism 4). Store only the hash, plus password_algo and parameters so a future upgrade can rehash on next login.
Login returns the same generic error for unknown email and wrong password, 401 {code: invalid_credentials}, and takes roughly the same time in both cases by running a dummy Argon2id verify for unknown users. That blocks account enumeration by timing and by message. Rate limit by IP and by account: for example 5 failed attempts per account in 15 minutes triggers a 15 minute lockout with exponential backoff, and a CAPTCHA after repeated failures. Log every attempt with user id, tenant id, IP, and result for audit, without logging passwords or tokens.
// Node.js 20, checked against argon2 npm package
import { hash, verify, argon2id } from "argon2";
const params = { type: argon2id, memoryCost: 65536, timeCost: 3, parallelism: 4 };
export async function hashPassword(plain: string) {
return hash(plain, params);
}
export async function verifyPassword(storedHash: string, plain: string) {
return verify(storedHash, plain);
}Sessions, tokens, and reset
For the browser, use a server-side session with an opaque session id in a cookie: HttpOnly; Secure; SameSite=Lax; Path=/. Server-side storage means revocation on logout, password change, or admin action is immediate. For the mobile app, use a short-lived access token (15 minutes) plus a refresh token (30 days) that rotates on every use. Store refresh tokens hashed in the database, grouped into a family, so reuse of an old token revokes the whole family and raises an alert. That detects token theft instead of silently accepting it.
Password reset and email verification follow the same pattern: generate a 32 byte random token, store only its SHA-256 hash, expire it in 30 minutes, make it single use, and send the raw token by email. Requesting a reset for an unknown email returns the same 202 response as for a known one.
| Event | What the client sees | What the server stores |
|---|---|---|
| Login success | 200, session cookie set | Session id hash, tenant id, expiry |
| Login failure | 401 invalid_credentials | Attempt log, failure counter |
| Refresh token reuse | 401, family revoked | Alert, all family tokens invalidated |
| Password reset request | 202 regardless of account | Hashed token, 30 minute expiry |
| Password changed | All sessions revoked | New Argon2id hash, audit entry |
MFA and tenant isolation
Offer TOTP as an optional second factor, required for admin roles in ERP tenants. Store the TOTP secret encrypted at rest, accept a 30 second clock window, and provide 10 single-use recovery codes hashed like passwords. MFA enrollment requires a fresh login and password confirmation.
Tenant isolation is enforced in the data layer: every table carries tenant_id, every query adds WHERE tenant_id = :current_tenant, and tenant_id comes from the session, never from a request body. A test that logs in as tenant A and requests tenant B's customer by id must return 404, not 403, so the existence of other tenants is not leaked. Add a database row level security policy as a second line of defence where the Postgres deployment supports it.
What I would not do
I would not put a long-lived JWT in localStorage, accept passwords over plain HTTP, store reset tokens in plain text, or return distinct errors for unknown users. I would also not roll my own crypto. Argon2id, TOTP, and token generation come from maintained libraries, and the whole flow gets a threat model review and penetration test before it touches production ERP data.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-8Describe a time you had to optimize a piece of code; what was the impact?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I worked on a sales-order listing service in a multi-tenant ERP, Java 17 on Spring Boot with PostgreSQL. The list endpoint for the web UI was timing out during the morning peak, when hundreds of branches opened the same screen. I profiled it before touching code, found an N+1 query pattern plus a missing composite index, and fixed both. Page p95 went from 2.4 seconds to 210 ms, database queries per page fell from 181 to 4, and we could hold the peak without adding database connections.
What I measured first
The symptom was slow UI loads, not an error. APM showed the endpoint itself was fast, but time in the database dominated. I pulled the slow query log and counted statements for one page of 50 orders.
| Metric, one page load | Before | After |
|---|---|---|
| SQL statements | 181 | 4 |
| p95 latency | 2,400 ms | 210 ms |
| Database CPU at peak, 40 req/s | 78% | 31% |
| Rows returned to build the page | 50 orders, then 50 customers, then 130 item rows in separate trips | 50 orders, 50 customers and 130 items in 3 batched trips |
The arithmetic explained the latency. One query fetched the orders. Then the serializer touched order.customer and order.items for each row, so Hibernate issued one customer query and one items query per order. That is 1 + 50 + 130 = 181 round trips. At roughly 12 ms per round trip under load, the queries alone account for over 2 seconds. No amount of JVM tuning would fix that.
The change
I replaced lazy loading in the loop with explicit batch fetching, and paginated in two steps so a join did not duplicate order rows.
// Before: lazy access inside the mapping loop, one query per order
for (Order o : orders) {
dto.setCustomerName(o.getCustomer().getName());
dto.setItemCount(o.getItems().size());
}
// After: page the order ids first, then fetch associations in batches
List<Long> ids = orderRepository.findIdsByTenantAndStatus(
tenantId, status, pageable);
List<Order> orders = orderRepository.findByIdsWithCustomer(ids);
Map<Long, List<Item>> itemsByOrder =
itemRepository.findByOrderIdIn(ids).stream()
.collect(groupingBy(Item::getOrderId));The second change was the index. The filter was tenant_id plus status plus created_at, but the existing index started with status alone, so Postgres scanned orders from other tenants and discarded them. I added:
CREATE INDEX CONCURRENTLY idx_orders_tenant_status_created
ON orders (tenant_id, status, created_at DESC, id DESC);CONCURRENTLY mattered because this table had about 40 million rows and we could not take a write lock during business hours. The index also supports the keyset cursor we moved to, so page 2 does not scan and discard page 1.
Impact, trade-offs and failure modes
At 40 requests per second, dropping from 181 to 4 statements cut database CPU from 78% to 31% and freed the connection pool. We had been hitting the 20-connection limit and queueing requests, which is why p99 was worse than p95. After the fix we deferred a planned pool increase and a read replica.
The trade-off is memory and write cost. Batch fetching loads the full page into memory, which is fine at 50 rows but would be risky at 1,000, so I capped the batch at the page size and kept the two-step approach instead of a single fetch join that can return duplicate orders. The new index adds roughly 8% to insert cost on that table, which we accepted because reads outnumber writes by about 20 to 1 on this workload.
Two failure modes I watch for now. First, a developer reintroduces lazy loading in a new DTO and the query count creeps back. I added an assertion in tests that fails if a page load issues more than 10 statements, and an APM alert on statements per request. Second, the index helps only while tenant_id is always present. A report query without it would fall back to a scan, so I check the slow query log weekly for any new pattern over 500 ms. That is how I know the fix held, rather than assuming it did.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-9How do you ensure your code is testable and maintainable?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I design for testability before I write the test. That means the business rule lives in plain code with its dependencies passed in, and the database, HTTP layer and ERP framework sit at the edges. If I can run the rule in a unit test with no container, no database and no network, it is testable. If changing a tax rule means editing a controller and a SQL script, it is not maintainable.
At TOTVS that distinction matters because a lot of the estate is legacy ERP code where the framework owns the transaction, the session and sometimes the screen. I keep new logic out of that. A fiscal or inventory rule goes into a small domain class. A thin adapter calls it from the ERP module, the REST endpoint or the batch job. Then I can test the rule once and reuse it, instead of copying it into three places that drift.
What that looks like in code
Java 17, no framework in the domain class:
public final class InvoiceTotals {
public record Line(long amountCents, int quantity, int taxBasisPoints) {}
public static long totalCents(List<Line> lines) {
long total = 0;
for (Line line : lines) {
long gross = line.amountCents() * line.quantity();
long tax = gross * line.taxBasisPoints() / 10_000;
total += gross + tax;
}
return total;
}
}The service that uses it depends on an interface, not on a concrete repository or a static ERP call:
public class IssueInvoiceService {
private final InvoiceRepository invoices;
private final FiscalGateway fiscal;
public IssueInvoiceService(InvoiceRepository invoices, FiscalGateway fiscal) {
this.invoices = invoices;
this.fiscal = fiscal;
}
public InvoiceId issue(InvoiceDraft draft) {
long total = InvoiceTotals.totalCents(draft.lines());
InvoiceId id = invoices.save(draft.withTotal(total));
fiscal.authorise(id);
return id;
}
}In a test I pass fakes for InvoiceRepository and FiscalGateway. No database, no fiscal provider, no waiting. I can also pass a clock and an ID generator the same way, which removes the two most common sources of flaky tests.
The arrows point inward. The domain rule knows nothing about the adapter. The adapter knows how to translate a request, not how to calculate tax.
How I decide what to test
I do not chase a coverage number. I test where a bug is expensive or hard to spot in review: money, tax, stock reservation, state transitions, and error paths that trigger a retry or a duplicate fiscal document.
| Test level | What it covers | Typical cost | Example from an invoice flow |
|---|---|---|---|
| Unit | One rule, fakes only | Milliseconds | totalCents with rounding at the line level |
| Integration | One adapter against a real dependency | Seconds, needs a container or test database | Repository saves and reloads an invoice with its lines |
| End to end | A user-visible path | Tens of seconds, brittle | Issue an invoice through the API against a stub fiscal gateway |
A worked trace for the unit test, with figures I would put in the test data:
| Line | Amount | Qty | Tax (bp) | Gross | Tax | Line total |
|---|---|---|---|---|---|---|
| A | 10_000 cents | 2 | 1_800 | 20_000 | 3_600 | 23_600 |
| B | 5_555 cents | 1 | 0 | 5_555 | 0 | 5_555 |
| Total | 29_155 |
If that trace fails, I know the rule is wrong. If an end to end test fails, I first check whether the rule test still passes. That ordering saves a lot of debugging.
Maintainability habits that make the tests stay useful
Small classes with one reason to change. A class that calculates tax, formats a PDF and calls the fiscal provider will change for three unrelated reasons, and its tests become a pile of mocks. I split it, and the split shows up in the test as a class I can instantiate directly.
Names that carry the domain language. reserveStock, releaseReservation and authoriseFiscalDocument tell a reader what should happen. processData and handle do not, and they hide the state machine I need to test.
Explicit contracts at the ports. The repository interface says what happens on a duplicate invoice number. The fiscal gateway interface says whether authorisation is idempotent. If those are not written down, tests pass against a fake that behaves differently from production.
Failure modes I watch for
Mocking everything. A test with six mocks usually tests the mock setup, not the code. I mock at the port, and I keep the number of collaborators per class low enough that a test needs two or three fakes at most.
Testing private methods or implementation details. That locks the code in place and makes refactoring feel dangerous, which is the opposite of maintainable. I test through the public method and assert on the result and on the calls made to the port.
Shared database state between tests. Tests that depend on rows left by another test pass locally and fail in CI in a different order. I reset the schema or use a fresh container per test class, and I never let a unit test touch a real database.
Uncontrolled time and randomness. A rule that reads LocalDate.now() directly cannot be tested for a month end or a fiscal calendar change. I pass a Clock in, and the test fixes the date.
When I inherit legacy code that cannot be changed in one pass, I start by extracting the rule behind a seam: a new class, a new interface, and a call from the old code to the new class. I add a characterisation test first that pins the current behaviour, even if the behaviour looks wrong, then I refactor under that test. That gives me a safe path instead of a big rewrite that nobody can verify.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-10Why do you want to work at TOTVS specifically?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I want to work at TOTVS because the engineering problems there are the ones I have been trying to get closer to for the last few years: large transactional systems, in a regulated domain, that cannot be rewritten in a weekend.
TOTVS is not a generic SaaS company that happens to sell ERP. It was founded in Brazil in 1983, it is headquartered in São Paulo, and its core products, Protheus, Datasul and RM, sit inside manufacturing, agribusiness, healthcare, retail and services companies across Latin America. That means the software has to handle Brazilian fiscal rules, payroll, inventory and multi-company structures correctly, at volume, for customers who have run on it for a decade or more. I find that combination interesting. A consumer app can forgive a wrong total. An ERP cannot. The tax calculation, the stock movement and the audit trail have to agree, and when they do not, someone in a factory or a hospital feels it the same day.
The second reason is the migration work. TOTVS is moving long-lived, on-premise and customised deployments toward cloud and SaaS delivery, while keeping integrations that customers built around the old systems. That is the work I want to do: strangler migrations, API layers in front of legacy modules, idempotent imports, and observability for batch jobs that run overnight. I have done smaller versions of that, and I would rather do it at a scale where getting the data model wrong is expensive and therefore taken seriously.
| What draws me to TOTVS | What I would bring to it |
|---|---|
| ERP and fiscal logic that must be provably correct, not approximately correct | Experience building transactional APIs with idempotent writes and audit logs |
| Legacy modernisation without breaking customer customisations | Strangler pattern work: new services in front of old modules, dual writes only where needed, rollback paths tested |
| Multi-segment scale: manufacturing, agribusiness, healthcare, retail | Performance work on high-volume batch and reporting jobs, with traces before rewrites |
| A Latin American product company, not a branch selling someone else's platform | Portuguese and English working fluency, and interest in building for Brazilian regulatory reality |
What I am not saying
I am not going to tell you I want to work at TOTVS because it is large, or because I admire its brand. That answer fits any large employer. Interviewers hear it as filler, and it gives them nothing to probe. The test I would apply to my own answer is whether it names a problem I would still want in six months. Mine does: how do you move a fiscal calculation that thousands of customers depend on, change its deployment model, and prove the numbers did not move.
If you push me on the team and the first months
I would ask which product area the role sits in, because Protheus, Datasul and the newer cloud products have different constraints, and I would rather be honest about where my experience transfers fastest. For the first 90 days I would expect to spend the first month reading the domain model and the incident history before proposing changes, the second month owning a bounded piece, such as an integration endpoint or a reporting query path, with tests and dashboards, and the third month taking on a migration or performance item with a clear rollback plan.
| Period | What I would be doing | How you would know it worked |
|---|---|---|
| Days 1 to 30 | Shadow on-call, read fiscal and inventory flows, map the modules my team owns | I can explain the main write paths and where they fail |
| Days 31 to 60 | Own one bounded change end to end, including metrics and alerts | Shipped behind a flag, with a documented rollback |
| Days 61 to 90 | Take a second item, ideally a legacy integration or a slow batch job | p99 latency or job duration measured before and after, on production-like data |
That is the honest version. I want the domain complexity, I want the migration scale, and I think my background in transactional systems and incremental modernisation is a direct fit for both.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-11Describe a situation where you had a disagreement with a team member; how did you resolve it?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
In my last role we were building an order service that had to check stock before confirming an order for a retail ERP client. I wanted the stock check to be synchronous inside POST /orders. My teammate, a senior backend engineer, wanted it async through a queue, because the synchronous call added latency to every order. We disagreed for two days and neither of us was fully wrong. I was worried about overselling, he was worried about checkout timing out during a peak sale. We resolved it by writing down the two failure modes, running a load test on both designs with the same traffic, and picking the synchronous check with a short timeout and a fallback to a reservation. Oversell dropped to zero in the test and p99 stayed under 200 ms.
What happened
The service sat in front of a legacy inventory module, similar in spirit to a Protheus-style ERP integration, where stock data lived in a database we did not own and updates arrived in batches. My concern was concrete: if we confirmed an order and the stock check failed later, the warehouse team would pick an item that did not exist and support would handle the cancellation. His concern was also concrete: during a promotion the inventory service took 900 ms at p95, and a synchronous call would push checkout past the gateway timeout.
We stopped arguing about architecture in the abstract and listed what each design would break.
| Design | Failure it prevents | Failure it creates | Measured in test |
|---|---|---|---|
| Synchronous check | Confirming an order with no stock | Checkout waits on inventory | p99 180 ms, 0 oversells in 10,000 orders |
| Async check via queue | Checkout stays fast | Order confirmed, stock fails 4 minutes later | p99 45 ms, 61 oversells in 10,000 orders |
| Synchronous check, 250 ms timeout, then reserve | Most oversells, bounded wait | Some orders go to manual review | p99 190 ms, 0 oversells, 0.4% to review queue |
The test used a replay of one week of production order traffic, scaled to 3x peak, against a staging copy of the inventory database. That gave us numbers we could both defend in the design review instead of preferences.
How the conversation stayed productive
I asked him to write his position in the ticket, and I did the same. That sounds small, but it stopped us from restating each other in meetings. When he said the queue would be fine because stock updates were frequent, I could point to the batch delay in the ERP feed, which was 15 minutes for some warehouses. When I said the synchronous call was safe, he pointed to the p95 latency graph from the previous promotion. Both points survived, so the compromise had to handle both.
We also agreed in advance on the decision rule: zero oversells was a hard requirement from the client, p99 under 250 ms was the checkout budget, and anything above 0.5% going to manual review would be a problem. The third design met all three. Neither of us got our original design, and we both signed off on the ticket because the rule, not seniority, made the call.
After release we added two alerts: one on the manual review queue depth, and one on inventory call timeouts. In the first month the timeout alert fired twice during a database maintenance window, and the fallback worked as designed. Orders went to review instead of failing checkout.
If I had pushed for my first design without the test, we would have shipped a checkout that timed out under load. If he had pushed for the queue without the test, we would have shipped oversells that the warehouse team would have found first. The disagreement was useful once we turned it into a test we both trusted.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-12Tell me about a project you are particularly proud of and your specific contribution to it.
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
At my previous company we ran order processing for mid-size retailers on a Java monolith. Every order went through one synchronous path: validate stock, reserve inventory, emit the fiscal document, then capture payment. When the fiscal service slowed down, checkout slowed down with it. p99 for POST /orders was 1.8 seconds, and during a promotion with 400 concurrent checkouts the thread pool saturated and we started timing out checkouts that were actually fine.
I proposed splitting the path at the fiscal boundary. The checkout service would validate, reserve stock, persist the order as PENDING_FISCAL, and publish an event. A separate worker would emit the fiscal document and publish a confirmation. Only then would payment capture proceed. My contribution was the design of that split, the outbox pattern that made it safe, and the migration of the fiscal consumer and the payment capture step.
The result after rollout: checkout p99 dropped to 210 ms, fiscal failures stopped blocking checkout, and we could retry fiscal emission independently.
Why the split was not just "make it async"
The hard part was the window between "order saved" and "fiscal document issued". In that window the order exists, stock is reserved, but payment has not been captured and there is no fiscal document. If the process died in that window, we needed to know on restart exactly which orders were stuck and resume them without double-emitting a document or double-capturing payment.
I used the transactional outbox. The order row and the outbox row are written in the same database transaction. A relay polls the outbox and publishes to the broker. Consumers are idempotent on order_id.
// Java 17, Spring Boot 3, checked against the outbox table
@Transactional
public Order createOrder(CreateOrder cmd) {
Order order = orders.save(Order.pending(cmd));
outbox.save(OutboxEvent.of("order.created", order.id(), order.payload()));
return order;
}If the transaction commits, the event will eventually be published. If it rolls back, neither row exists. That removed the dual-write problem between the database and the broker.
Worked trace of a failure
| Time | Event | State |
|---|---|---|
| 0 ms | POST /orders arrives | checkout validates stock |
| 40 ms | transaction commits | order PENDING_FISCAL, outbox row written, customer sees "order received, payment pending" |
| 55 ms | relay publishes order.created | broker ack |
| 120 ms | fiscal worker starts emission | calls fiscal service |
| 900 ms | fiscal service returns 503 | worker marks attempt failed, backs off |
| 5 s | retry succeeds | fiscal document NF-88412 stored |
| 5.1 s | worker publishes order.fiscal_confirmed | payment capture proceeds |
The customer did not see a confirmed, paid order at 40 ms. They saw an accepted order in PENDING_FISCAL state, with payment not yet captured. Capture waited for the confirmation event, which preserves the original ordering where fiscal emission came before payment. If the worker had crashed at 120 ms, the outbox row would still be unpublished or the attempt counter would show the failure, and the relay would resume it on restart.
What I measured and what I would not do again
Before the change, fiscal latency was coupled to checkout latency. After, we tracked three numbers separately: checkout p99, time from order creation to fiscal confirmation, and outbox lag. Outbox lag stayed under 2 seconds at peak. Fiscal confirmation p95 was 4 seconds, which we accepted because the customer was no longer waiting on it at checkout, only seeing the pending state.
I initially wanted to move inventory reservation into the same worker. That was a mistake. Reservation has to be synchronous, because the customer needs to know at checkout whether the item is available. Keeping reservation in the checkout transaction and moving only fiscal emission out kept the consistency boundary where the business actually needed it.
The trade-off we accepted: eventual consistency on the fiscal document and on payment capture. The order page showed "fiscal document being issued, payment pending" for a few seconds. We made that state explicit in the API instead of hiding it, and support tickets about missing documents dropped because customers could see the state and we could point to the attempt log.
If I ran it again
I would add a dead-letter alert on outbox rows older than 60 seconds from the start, rather than discovering stuck orders from a manual report. I would also version the event payload from day one. We had to add a field in month three and consumers on the old version silently ignored it, which cost us a day of debugging.
The part I am proud of is not the queue. It is that we moved the slow, failure-prone step out of the checkout path without weakening the guarantee that every accepted order eventually gets its fiscal document before payment is captured, and we proved it with the outbox lag and confirmation metrics instead of hoping the broker would handle it.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-13How do you stay updated with new technologies?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I treat staying current as a pipeline with a fixed time budget, not as reading everything. At TOTVS that matters because we maintain long-lived ERP and Fluig workloads alongside newer cloud services. A technology that is excellent in a startup can still be a bad fit if it breaks a client on Protheus, RM, or a fiscal rule that has to stay stable for years.
My budget is about 90 minutes a week: 30 minutes on primary sources and 60 minutes building something small. Primary sources come first. For the stack I actually run, that is the Java, TypeScript, React, Node.js, and .NET release notes, RFCs, and vendor changelogs, plus TOTVS product notes for Fluig and our cloud platform. I use engineering blogs and conference talks only to find candidates, then I verify the claim in the release notes or the source.
Nothing reaches production from a blog post. A candidate technology gets a spike behind a feature flag, with a written adoption gate before I propose it to the team.
| Source type | What I use it for | Signal quality | Latency |
|---|---|---|---|
| Language and framework release notes | Breaking changes, deprecations, migration path | High, it is the contract | Days after release |
| RFCs and specifications | Protocol and API behaviour I depend on | High | Slow, but stable |
| Vendor changelog for our deployed version | Security fixes, behaviour changes in our exact version | High | Same day |
| Maintainer blog or conference talk | Candidate ideas to spike | Medium, check against docs | Weeks early |
| Social posts and aggregators | Discovery only | Low | Fast, noisy |
How I evaluate a candidate, with a worked example
Hypothetical example, labelled as such: evaluating Java 21 virtual threads for a hypothetical order lookup service that currently blocks on database calls. The spike is a branch, not a rewrite.
// Java 21, checked against the JDK 21 release notes
try (ExecutorService executor =
Executors.newVirtualThreadPerTaskExecutor()) {
Future<Order> future = executor.submit(() -> orderRepository.findById(id));
return future.get(2, TimeUnit.SECONDS);
}I score it before any rollout proposal:
| Criterion | Threshold I set in the spike | Hypothetical result |
|---|---|---|
| p99 latency at 500 concurrent requests | No regression vs platform threads | 41 ms vs 44 ms, within noise |
| Memory at same load | No more than 15% increase | 8% increase |
| Behaviour under a slow database | Threads block cheaply, timeouts still fire | Timeouts fired at 2 s as coded |
| Operational cost | No new infrastructure to run it | None, JDK upgrade only |
| Exit cost | Can revert in one deploy | Yes, executor swap behind a flag |
If two criteria fail, I stop and write the decision down. That record is what stops the same debate returning in six months, and it gives the next engineer the numbers instead of my opinion.
Failure modes I watch for
Tutorial hell is the common one. Reading ten articles about a framework and building nothing leaves me unable to answer the questions that matter in production, such as what happens when a connection pool saturates. The spike fixes that because it forces a failure. In the example above, the failure to look for is a downstream call that ignores interruption, which would pin virtual threads and hide the timeout.
The second failure mode is adopting on hype. A new library can win on features and lose on maintenance, for example a single maintainer, no security policy, or a licence that conflicts with a commercial ERP product. I check those three things in the spike notes before I recommend anything.
The third is version drift inside TOTVS itself. Staying current with the newest release while our clients run an older supported version creates a gap between what I test and what ships. I keep a personal matrix of the versions we support, and I read the changelog for the oldest supported version, not only the newest. That is where breaking changes and security fixes actually affect us.
What I would not do is chase every release. For a long-lived enterprise codebase, I adopt on the LTS or supported cadence, and I let the spike decide. That keeps the learning real, the rollout reversible, and the decision defensible to a team that has to run the result.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-14What motivates you to learn new skills outside of your daily tasks?
Reported in TOTVS Software Engineer Interview Questions & Guide 2026
The 90-second answer
I learn when a gap in my daily work blocks me from shipping something I can defend. A few years ago I was building CRUD screens and integrations against a legacy ERP, and every change turned into a long transaction, a timeout, and a support ticket. I could make the feature work, but I could not explain why it failed under load or how to make the integration safe to retry. That gap, not a course catalogue, set my next learning target.
So I pick one gap, build a small experiment against it within two weeks, and try to use the result in production or in a team talk. If there is no artifact after two weeks, I drop the topic. That rule keeps me from collecting tutorials.
How I choose and sustain it
My budget is concrete. I reserve 3 hours a week, which is about 150 hours a year after holidays and on-call weeks. I split it roughly 60% building, 25% reading primary sources, and 15% writing or presenting. The split matters because reading alone does not change how I code on Monday.
Recent examples, with the trigger stated plainly:
| Skill I pursued | Trigger in daily work | Artifact | Result |
|---|---|---|---|
| Idempotency and outbox patterns | Retried ERP integration created duplicate postings | Small Node.js service with Idempotency-Key handling and a retry trace | Adopted in one integration; duplicate rate fell in staging load tests |
PostgreSQL indexing and EXPLAIN ANALYZE | A list query went from 40 ms to 900 ms as the table grew | Before/after query plans for a real endpoint | Composite index cut p95 to 110 ms in a staging replica |
| Event-driven design basics | Point-to-point integrations made change impact hard to trace | Sequence diagram and a prototype consumer for one order event | Used in a design review, even though we did not adopt the full pattern |
What I avoid, and how I notice it
The failure mode I watch for is tutorial hell: finishing modules, feeling productive, and shipping nothing. My check is the artifact column above. If I cannot point to code, a benchmark, or a document a teammate used, the learning did not count.
A second failure mode is learning a fashionable tool that does not fit the constraints I actually have. At TOTVS scale, with long-lived customers and integrations that must keep working for years, I ask whether a new approach handles partial failure, backfills, and audit trails. If the answer is unclear, I read the vendor documentation and the relevant RFC or specification first, then run a load test with realistic data volumes before I recommend anything.
Burnout is the third one. Learning outside work only works if it stays bounded. When the 3 hours start eating into sleep or on-call recovery, I cut the experiment short rather than letting it sprawl. A dropped experiment with a written reason is a better outcome than a half-finished side project that leaves me tired for the job I was hired to do.
What motivates me, in short, is closing a gap I can name, proving the fix with a small artifact, and seeing a teammate reuse it. That loop has kept me learning for years without turning it into credential collecting.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-15Tell me about how you handle teamwork, what you do in your free time, and what you would like to improve?
Reported in Teamwork and Personal Profile
The 90-second answer
I will take the three parts in order, with a concrete example for the first and third.
Teamwork. I work best in small, cross-functional squads where decisions are written down before code starts. In my last role, a squad of six (two backend, two frontend, one QA, one product owner) owned a billing integration used by about 400 enterprise clients. We used a short RFC for any change touching the public API or the database schema, async updates in a shared channel twice a week, and a 24-hour target for first review on pull requests. That last rule mattered more than the tooling. Reviews stalled when the author was the only person who understood the legacy fiscal rules, so I started pairing for 30 minutes on those PRs instead of leaving comments back and forth.
A specific case: we had to migrate a nightly batch job that calculated invoices. The old job ran for 3 hours and failed silently on malformed customer records. My teammate wanted a full rewrite in a new service. I wanted to keep the existing job and add validation first, because a rewrite would miss edge cases we had not documented. We agreed on a middle path. We added a validation report for two weeks, which showed 1.8% of records had missing tax codes, then rewrote the calculation behind a feature flag with the old job as fallback. The new job ran in 42 minutes, and we could compare outputs row by row before switching. The disagreement was about risk, not about who was right, and the data from the report settled it.
What I do in practice, beyond that example: I state my assumptions in the PR description, I flag when I am blocked the same day rather than at the standup, and I take my turn on on-call and on the unglamorous work, such as fixing flaky tests and updating runbooks. In a large product company like TOTVS, where teams are distributed across offices and time zones, that written context is what lets someone else pick up your work without waiting for you.
Free time. I run three times a week, and I spend one evening a week on a small side project. Right now it is a tool that imports CSV exports from a legacy ERP and checks them against a set of fiscal validation rules, which is a simplified version of problems I see at work. I also read one technical paper or RFC a month and write a short note on what I would actually change in our codebase because of it. I am not trying to impress anyone with the volume. The point is to stay curious about areas outside my immediate stack, and to have something concrete to discuss when I mentor junior developers in a local meetup group.
What I would like to improve. My weakest area is estimating work on legacy integrations, especially when the documentation is incomplete. In the last two quarters, I underestimated a migration by about 30% because I counted the happy path and missed the data cleanup and the client communication. I am addressing it directly:
| Area | Evidence | Action I am taking | How I will know it worked |
|---|---|---|---|
| Estimating legacy work | Two estimates 25 to 30% low in the last six months | Break estimates into discovery, build, data cleanup, and rollout, and add a 20% buffer for undocumented rules | Track estimate versus actual on the next three tickets |
| Writing design docs | My PRs were clear on code but thin on alternatives considered | Write a one-page RFC for any change over five days of effort, and ask a senior engineer to review the draft | Fewer review rounds on schema and API changes |
| Giving feedback early | I waited until a design was finished before raising concerns | Raise risks in the RFC stage, in writing, with a proposed alternative | Risks raised in week one instead of week three |
I chose estimating because it affects the team, not just me. A missed estimate pushes work onto teammates at the end of a sprint. The other two items support the same goal: clearer writing makes my estimates and my concerns visible earlier, when they are still cheap to fix.
If I join TOTVS, I would expect to learn a lot about large-scale ERP and fiscal domains that I have only touched from the outside. That is part of why I am interested in the role. I can contribute on the engineering practices above from day one, and I would use the first months to build the domain knowledge that makes those practices more effective here.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-16How would you identify and troubleshoot performance issues in a slow SQL query?
Reported in Diagnosing SQL Query Slowness
The 90-second answer
I start by proving the query is the problem, not the network, the connection pool, or a lock. I find the exact SQL and its parameters from pg_stat_statements or the slow query log, reproduce it against production-like data volume, and read its execution plan with EXPLAIN (ANALYZE, BUFFERS). The plan tells me where time goes: a sequential scan on a large table, a join that explodes rows, a sort or hash aggregate spilling to disk, or an index scan that still reads millions of rows. I fix that node, not the whole query, then re-run the same plan and check p95 in production.
Assume PostgreSQL, which is what most Totvs services I have worked with run. The steps are the same on other engines, only the plan syntax changes.
1. Identify the real offender
A slow endpoint is not a slow query. I rank queries by total time, not by single execution, because a 20 ms query run 50,000 times a day costs more than a 2 s query run twice.
SELECT query, calls, round(mean_exec_time::numeric, 1) AS mean_ms,
round(total_exec_time::numeric, 1) AS total_ms
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;I then pull the parameters for the top entry. Without parameters a plan can mislead: a prepared statement planned for customer_id = 1 may use a different index than the same query for a customer with 200,000 orders.
2. Read the plan as a trace
EXPLAIN (ANALYZE, BUFFERS, FORMAT TEXT)
SELECT o.id, o.total, c.name
FROM orders o
JOIN customers c ON c.id = o.customer_id
WHERE o.status = 'open' AND o.created_at >= now() - interval '30 days'
ORDER BY o.total DESC
LIMIT 50;A worked trace from a real incident, figures from that run:
| Node | Actual time | Rows | Estimated rows | What it means |
|---|---|---|---|---|
| --- | --- | --- | --- | --- |
| --- | --- | --- | --- | --- |
| Sort | 1,840 ms | 50 | 50 | Sorting the full result before LIMIT |
| Hash Join | 1,790 ms | 412,000 | 38,000 | Estimate off by 10x, hash table built over too many rows |
Seq Scan on orders | 1,620 ms | 412,000 | 38,000 | No index on (status, created_at) |
| Hash | 210 ms | 90,000 | 90,000 | Customers table, fine |
Two signals matter here. First, Seq Scan on 412,000 rows for a 50 row result. Second, the estimate mismatch. That mismatch usually means stale statistics, a skewed column, or a parameter the planner cannot see. I check ANALYZE orders; history and the distribution of status before I add an index blindly.
3. Fix the node, and know when not to
For the trace above, a composite index matches the filter and the sort:
CREATE INDEX CONCURRENTLY idx_orders_open_created_total
ON orders (status, created_at, total DESC);CONCURRENTLY matters in production. A plain CREATE INDEX takes a lock that blocks writes on a busy ERP table. After the index, the same plan should show an index scan returning roughly 50 rows after the sort, not 412,000.
Other fixes I reach for, in order of how often they apply:
| Symptom in plan | Likely cause | Fix |
|---|---|---|
| Seq scan on filtered column | Missing or unused index | Composite index in filter order, check pg_stat_user_indexes for unused ones |
| Nested loop with huge inner rows | Join order or missing join index | Index on the foreign key, or rewrite as a hash join with a filtered subquery |
Function on indexed column, e.g. WHERE date(created_at) = ... | Index cannot be used | Rewrite as a range, or add an expression index if the rewrite is impossible |
Rows Removed by Filter large | Index returns too much | Narrow the index or add the missing predicate |
| Sort node dominates | ORDER BY over large set | Index that provides order, or paginate with a keyset instead of OFFSET |
I do not add an index for every slow query. Each index slows writes, uses disk, and can mislead the planner if statistics are stale. If the query runs twice a day and takes 3 s, a materialized view or a scheduled summary table is cheaper than an index on a write-heavy table.
Failure modes I check before calling it done
Locks: EXPLAIN ANALYZE runs the query, so I never run it unguarded on a write query in production. I wrap it in a transaction and roll back, or run it on a replica.
Parameter sensitivity: I test with the worst customer, not the average one. A plan that is fast for 10 orders can be catastrophic for 200,000.
Bloat and cache: Buffers shows shared hits versus reads. If reads dominate, the working set does not fit in cache and the fix may be reducing rows read, not adding another index.
After the fix I compare the new plan, the mean and p95 from pg_stat_statements, and the endpoint latency. If p95 does not move, the query was not the bottleneck and I go back to the pool, the ORM fetching row by row, or a downstream call.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-17Describe how you think about the day-to-day tasks you would handle and the organization needed to deliver them?
Reported in Career and Day-to-Day Expectations
The 90-second answer
I would organize my day around flow, not a long to-do list. At TOTVS that matters because the work is rarely greenfield. A ticket might be a fiscal rule in an ERP module that has run for 15 years, a bug in a modern TOTVS Tech service in Java or TypeScript, or a change in Fluig that a customer team depends on for their closing process. The common thread is the same: reproduce the problem, make the smallest safe change, prove it with tests, ship it behind a flag or a reversible migration, and watch it in production.
My personal system has three parts. One board with one column per state, a work-in-progress limit of two active items, and a fixed daily rhythm for reviews, focus work, and on-call checks. If a third item starts, something else stops or moves to tomorrow explicitly. That is the organization that lets me deliver without dropping the ticket I already promised.
What a typical day looks like
I start by checking what changed overnight: failed pipelines, alerts for services I own, and review requests. Then I pick the highest-value ticket that is ready, meaning I can state the acceptance criteria and the data I need to reproduce it. I timebox investigation to 90 minutes. If I cannot reproduce or scope it by then, I write down what I know, what I tried, and the next experiment, and I ask for help in the ticket rather than silently burning a day.
A hypothetical week, labelled as an example, shows the rhythm:
| Block | Monday | Tuesday | Wednesday | Thursday | Friday |
|---|---|---|---|---|---|
| 09:00 | Triage, alerts, reviews | Reviews, pairing | Triage, alerts, reviews | Reviews, pairing | Reviews, release check |
| 10:00 | Focus: ticket A | Focus: ticket A | Focus: ticket B | Focus: ticket B | Focus: ticket A follow-up |
| 14:00 | Focus: ticket A | Demo prep, docs | Focus: ticket B | Deploy, monitor | Retrospective, cleanup |
| 16:00 | Standup, unblock others | On-call handover | Standup, unblock others | On-call handover | Plan next week |
Focus blocks are 90 minutes with notifications off. Reviews are batched twice a day, not answered as they arrive. That protects deep work and still keeps review latency under a day, which is what the team actually feels.
How I keep it organized
My board mirrors that flow: Ready, Doing, In Review, Waiting, Done. Waiting is a real column, not a hidden pile. If a ticket waits on a customer data extract or a DBA window, it sits there with an owner and a next action date. I review the board at 09:00 and 16:00 and move anything stale.
The arithmetic behind the WIP limit is simple. With four active tickets, I switch context at least four times a day. At roughly 20 minutes to reload a legacy ERP codebase, its data model, and the fiscal rule I was holding in my head, that is 80 minutes lost, about 20 percent of a focused day. With two active tickets, the loss drops to about 40 minutes and, more importantly, I finish things. Finished work that is deployed beats three half-done tickets at sprint end.
I also keep a small script for my own capacity check at sprint planning. It is not a planning tool for the team, just a guardrail for me:
# Python 3.11, checked against CPython 3.11
def capacity(days=5, hours_per_day=6, focus_ratio=0.7, wip=2):
focus_hours = days * hours_per_day * focus_ratio
return {"focus_hours": round(focus_hours, 1), "wip_limit": wip}
print(capacity())
# {'focus_hours': 21.0, 'wip_limit': 2}Six focus hours a day is already optimistic once meetings and on-call are counted. Twenty-one focus hours in a sprint means I should commit to two or three tickets, not five, and say so early.
Where this breaks, and what I do then
Legacy work breaks the plan. A Protheus or AdvPL change can look like a one-line fix until I find a customisation a customer made in 2012 that depends on the old behaviour. My detection is the reproduction step. If I cannot reproduce the reported behaviour on a clean base, I stop and ask for the customer's exact version, parameters, and a data extract under the privacy rules. Guessing in a fiscal module creates a second incident.
Production breaks the plan too. If I am on call, the board is paused and the incident owns the day. I hand over my Doing ticket with a note on what is safe to leave overnight, what is half-migrated, and what test I was about to run. The failure mode I avoid is leaving a half-finished change in a branch that someone else picks up without context.
At the end of the week I close the loop in the ticket itself: what shipped, which version, what metric or log I checked, and what I would do differently. That record is what makes the next person, and the next me, faster. It also turns a busy week into evidence of delivery, which is the point of the organization in the first place.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-18Tell me about a personal habit you consider different.
Reported in Personal Quirk
The 90-second answer
I write a falsifiable prediction before I look at logs. One line in a scratch file: what I think happened, what evidence would prove it, and what I will check first. It takes about two minutes and it stops me anchoring on the first stack trace I see.
Most debugging starts with reading. In a large ERP codebase, like the order and billing flows at TOTVS, that is risky. There are legacy modules, cached totals, and batch jobs that also write the same tables. The first log line is often real and still not the cause. Writing the prediction first makes my later reading a test instead of a story I build around whatever I find.
A concrete case. An order total in a test environment was R$ 1.240,00 higher than the sum of its items. My prediction, written before I opened anything, was: "A retry of the pricing service wrote the discount twice. I will check the idempotency key table for duplicate keys on order 8841, and I expect two rows."
The trace looked like this:
| Step | What I checked | Result |
|---|---|---|
| 1 | Prediction written at 14:03 | Duplicate discount from a retry |
| 2 | Idempotency keys for order 8841 | One key, one row. Prediction wrong. |
| 3 | order_items history for the discount row | Created by a nightly batch at 02:00, not by the API |
| 4 | Batch job log | It reapplied a promotion that the API had already removed |
| 5 | Fix | Added a guard in the batch: skip if promotion_id already present on the order |
That wrong prediction saved time rather than wasting it. Because I had committed to a check, I ruled out the retry path in under five minutes instead of spending an hour reading pricing code that was not involved. I then had a clean second hypothesis to test against the batch history.
I keep the log in a tiny script so the format stays consistent even when I am tired or on call:
# log_prediction.py, Python 3.12
from datetime import datetime
def log_prediction(incident: str, prediction: str, check: str) -> None:
stamp = datetime.now().strftime("%Y-%m-%d %H:%M")
with open("predictions.md", "a", encoding="utf-8") as f:
f.write(f"- {stamp} | {incident} | {prediction} | Check: {check}\n")The habit loop itself is deliberately small:
Two failure modes are worth naming. If the prediction is vague, such as "something with caching", it tests nothing. I force myself to name a table, a key, or a timestamp. If I skip the step during an outage because it feels slow, I lose the benefit exactly when anchoring is most likely. The two minute cost is the point. It is cheaper than chasing a plausible but wrong cause through a codebase I did not write.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-19Explain what triggers are in SQL.
Reported in SQL Triggers Basics
The 90-second answer
A trigger is stored database code that runs automatically when a specified event happens on a table, usually INSERT, UPDATE, or DELETE. You do not call it from the application. The database fires it inside the same transaction as the statement that caused it, so if the trigger fails, the original change rolls back.
That last point is the whole design. A trigger is not a scheduled job and it is not a stored procedure you invoke. It is a reaction to a data change, and it inherits the transaction, locks, and permissions of that change.
Timing and granularity
Two choices define a trigger. Timing: BEFORE runs before the row change is applied, AFTER runs after. Granularity: row-level runs once per affected row, statement-level runs once per statement.
| Type | When it runs | Typical use |
|---|---|---|
BEFORE INSERT/UPDATE | Before the change, can modify the incoming row | Derive a field, reject an invalid value, set updated_at |
AFTER INSERT/UPDATE/DELETE | After the change, sees the committed-in-transaction state | Write an audit row, update a summary table, publish a change record |
INSTEAD OF | Replaces the action on a view | Make a complex view writable, route writes to base tables |
PostgreSQL and Oracle support row and statement triggers. SQL Server supports AFTER and INSTEAD OF triggers, with BEFORE covered by INSTEAD OF on the table. The concepts transfer, the syntax does not.
Worked example: order and stock
Assume an ERP-style schema at Totvs scale: orders and stock. An AFTER INSERT trigger on orders decrements stock and writes an audit entry. In PostgreSQL:
CREATE OR REPLACE FUNCTION trg_order_stock()
RETURNS trigger AS $$
BEGIN
UPDATE stock
SET qty = qty - NEW.qty
WHERE product_id = NEW.product_id
AND qty >= NEW.qty;
IF NOT FOUND THEN
RAISE EXCEPTION 'insufficient stock for product %', NEW.product_id;
END IF;
INSERT INTO order_audit (order_id, product_id, qty, created_at)
VALUES (NEW.id, NEW.product_id, NEW.qty, now());
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER order_stock_trg
AFTER INSERT ON orders
FOR EACH ROW EXECUTE FUNCTION trg_order_stock();Trace for INSERT INTO orders (id, product_id, qty) VALUES (42, 7, 3) when stock.qty for product 7 is 10:
| Step | What happens | State |
|---|---|---|
| --- | --- | --- |
| --- | --- | --- |
| 1 | Statement inserts order 42 in the transaction | Order visible only inside the transaction |
| 2 | AFTER INSERT trigger fires once for that row | NEW holds id 42, product 7, qty 3 |
| 3 | Trigger updates stock: 10 - 3 | stock.qty = 7, still uncommitted |
| 4 | Trigger inserts into order_audit | Audit row present in the transaction |
| 5 | Transaction commits | Order, stock change, and audit become visible together |
If stock had been 2, step 3 would update no row, FOUND would be false, and the RAISE EXCEPTION would roll back the order insert as well. That atomicity is why teams put invariants in triggers instead of relying on the application to check first and write later.
When I would not use one
Triggers hide logic. A developer reading the application code will not see that inserting an order also writes an audit table and changes stock. At high volume that also costs you: a row-level trigger on a bulk load of 1 million rows fires 1 million times, and each firing can take locks on the same stock row, which serialises the load.
I prefer application or service-layer code when the logic needs branching, external calls, or unit tests. I prefer a trigger when the invariant must hold no matter which client writes, including a legacy ERP module, a batch import, or an ad hoc SQL fix. Audit trails are the classic case. If a DBA can update a table directly, only a trigger guarantees the audit row follows.
Failure modes to name in an interview
Recursive triggers: a trigger on orders that updates orders can fire itself. Most engines limit recursion depth and then error out, which is a symptom of a design problem, not a tuning problem.
Lock contention and deadlocks: an AFTER UPDATE trigger that touches a second table in a different order from another trigger can deadlock under concurrent order entry. The fix is a consistent access order across all triggers on the hot tables.
Silent performance cost: a trigger that does a lookup per row turns a set-based UPDATE of 500,000 rows into 500,000 lookups. If the trigger logic can be expressed as a set operation, I would rewrite it as one and keep the trigger only for the audit write.
So the short version I would give: triggers are event-driven, transactional database code. Powerful for enforcing invariants and audit trails close to the data, risky when they become a place to hide business logic that belongs in testable application code.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-20Describe a time you had to learn a new technology or proprietary language quickly to solve a problem?
Reported in Rapid Learning for Problem Solving
The 90-second answer
I had three working days to fix a stock reservation bug in a Protheus system written in ADVPL, a language I had never used. The bug blocked order picking at month end, and the vendor support queue was quoting five days. I did not try to learn ADVPL in general. I learned the slice I needed to reproduce the bug, change one function, and prove the fix in a sandbox, then I documented what I had learned for the next person.
The context: a distribution centre ran Protheus, our ERP, and a custom ADVPL routine reserved stock when an order was confirmed. After a patch, reservations were not being released for cancelled orders. Pickers saw stock as available in the UI but the reservation table still held it, so new orders failed with insufficient stock. About 1,200 orders were affected over a weekend, and month end close was on Thursday.
My plan was timeboxed and narrow:
| Time | Action | Output |
|---|---|---|
| Day 1, morning | Reproduced the failure in a sandbox copy with one product and two orders | Confirmed: cancel path never deletes the reservation record |
| Day 1, afternoon | Read the function and its callers, plus the ADVPL docs for the database functions it used | Found the cancel routine called a different table alias than the reserve routine |
| Day 2 | Wrote a minimal test script that reserves, cancels, and checks the table | Test failed before the fix, passed after |
| Day 3 | Deployed behind a parameter flag, monitored for one day, then removed the flag | No new stuck reservations in 48 hours |
The actual bug was small. The reserve routine wrote to a work table using one alias, and the cancel routine deleted using another alias that pointed at a different table after the patch. In ADVPL that looks like this in simplified form:
// Before: cancel deletes from the wrong alias
Function CancelReservation(cOrder)
DbUseArea(.T., "TOPCONN", "RESERVA", "R")
DbSelectArea("R")
DbSetIndex("RESERVA")
DbSeek(cOrder)
While !Eof() .And. R->ORDER = cOrder
RecLock("R", .F.)
Delete
MsUnlock()
DbSkip()
EndDo
Return .T.The fix pointed the delete at the same table and index the reserve path used, and added a check that the seek actually found a record before looping. That check mattered because the original code silently did nothing when the index did not match, which is why the failure was invisible in logs.
What I did to learn fast
I treated the language as a set of unknowns to shrink, not a course to complete. I listed the constructs in the failing function: DbUseArea, DbSeek, RecLock, MsUnlock. I looked up only those, in the vendor documentation, and ignored the rest of the language. I also found two existing ADVPL routines in the same codebase that did a similar delete correctly and used them as a reference implementation. That gave me a pattern to copy instead of inventing one.
I wrote the test script before the fix. It created a reservation, cancelled the order, and asserted the reservation count was zero. Running it against the original code showed the count stuck at one. That gave me a clear stop condition: I was done when that script passed and the existing order flow tests still passed.
Trade-offs and failure modes
Learning a proprietary language under deadline has a specific risk: you copy a pattern that works in the sandbox but breaks under concurrent access. ADVPL record locking is explicit, so a missing RecLock or a forgotten MsUnlock can leave a record locked for other users. I checked for that by running two sessions against the same order in the sandbox and confirming the second session could read the record after the first finished. I also kept the change to one function and put it behind a parameter, so if it misbehaved in production I could switch it off without a new deployment.
Another risk is that vendor documentation for older ADVPL versions describes functions that behave differently in the version you run. I verified each function against the sandbox rather than trusting the docs alone. The DbSeek behaviour with a mismatched index was exactly that case.
After the fix, I wrote a short internal note with the three functions I had learned, the alias mismatch pattern, and the test script location. The point was not to become an ADVPL expert in three days. It was to solve the problem, prove the solution, and leave the next engineer a shorter path in. If I had a week instead of three days, I would have spent the extra time on the surrounding fiscal routines. With three days, the right scope was one bug, one test, and a safe rollback.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Q&A-21How would you structure a component library for a large-scale enterprise application?
Reported in Designing a Large-Scale Component Library
The 90-second answer
I would treat the library as a product with internal consumers, not as a folder of shared components. At TOTVS scale that matters because the same library has to serve ERP screens, CRM, Fluig portals and partner integrations, each with different density, branding and release cadence, without forking the code.
I would build four layers in a monorepo, with dependencies pointing only downward:
| Layer | Contents | Example |
|---|---|---|
| Tokens | Colour, spacing, typography, elevation, motion as versioned JSON | color.action.primary.default |
| Primitives | Unstyled, accessible building blocks with no business meaning | Button, TextField, Dialog |
| Composite | Primitives composed for a repeated UI pattern | DataTable, DateRangePicker, SearchInput |
| Domain patterns | ERP or CRM specific assemblies, kept out of the core | CustomerSearch, FiscalDocumentStatus |
Primitives own behaviour and accessibility. Composite components own layout and common states such as loading, empty and error. Domain patterns live in a separate package so a CRM change does not force an ERP upgrade.
packages/
tokens/ # design tokens, generated CSS variables and TS types
primitives/ # Button, Input, Dialog, with Radix or React Aria under the hood
composite/ # DataTable, FormField, Pagination
patterns-erp/ # domain assemblies, depends on composite only
docs/ # Storybook, usage rules, migration guides
cli/ # codemods for breaking changesAPI and theming
Every component gets a narrow, typed API. I would use variants instead of boolean props, because booleans multiply states and hide intent.
// TypeScript, React 18
type ButtonProps = {
variant?: 'primary' | 'secondary' | 'danger';
size?: 'sm' | 'md' | 'lg';
loading?: boolean;
disabled?: boolean;
children: React.ReactNode;
};Theming comes only from tokens. A component never hardcodes #0057B8 or 16px. It reads a CSS variable, so a product can ship a different brand by swapping the token file. Density is a token set too (spacing.compact, spacing.comfortable), which is how the same DataTable works in a dense ERP grid and a spacious portal without a prop fork.
Governance, versioning and failure modes
Each package has a named owner team, an RFC for new primitives, and semantic versioning. A breaking prop change is a major version plus a codemod in cli/, for example renaming onClose to onDismiss across 400 call sites. Deprecation runs for at least two minor releases with a console warning in development and a migration note in Storybook.
Three failure modes I watch for:
- Prop explosion. When a primitive passes 25 props, it is really a composite in disguise. I split it and move the extra props up a layer.
- Bundle bloat. I set a budget, for example no primitive over 8 kB gzipped and the full primitives package under 120 kB gzipped, checked in CI. Tree shaking only helps if packages are split per component.
- Accessibility drift. Every primitive ships keyboard tests and axe checks in CI, plus visual regression snapshots for the four states: default, hover, focus, disabled. A component that fails focus visibility does not merge, however good it looks.
Adoption is measured, not assumed. I would track which components are imported by which app, how often a pattern is reimplemented locally, and the time to first correct usage in a new team. If teams keep copying a table into their own repo, the library is missing a composite, and that gap becomes the next RFC.
Curated: · Written: · Reviewed:
Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.
Curated: · Written: · Reviewed: